在 \foreach 循环内将参数传递给 \includegraphics

在 \foreach 循环内将参数传递给 \includegraphics

我正在尝试定义一个循环来在 Beamer 演示文稿中创建 4 张幻灯片。每张幻灯片都会有一个图形。下面是一个最小示例:

\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage{pgffor}

\usepackage{xstring}
% This works both with inline lists and with macros containing lists
\newcommand*\GetListMember[2]{\StrBetween[#2,\number\numexpr#2+1]{,#1,},,\par}%

\begin{document}

\def\views{isometric,side,front,back}

\foreach \view [count=\n] in \views
{
  \begin{frame}
    \frametitle{MY TITLE 1}
    \framesubtitle{My subtitle 1}
    n = \n (works)
    \def\filename{\GetListMember{\views}{\n}}
    Filename = \filename (works)
    This doesn't work:
    \begin{figure}
      \centering
      \includegraphics[width=\textwidth]{\filename}
    \end{figure}
  \end{frame}
}

\begin{frame}
  \frametitle{MY TITLE 2}
  \framesubtitle{My subtitle 2}
  This works:
  \begin{figure}
    \centering
    \includegraphics[width=\textwidth]{isometric}
  \end{figure}
\end{frame}

\end{document}

我不明白为什么循环内的 \includegraphics 不起作用,而循环外的却起作用。我收到的错误是:

! Undefined control sequence.
\filename@simple ...#2\\}\fi \edef \filename@base 
                                                  {#1}
l.27 }

有人能帮我找出我做错什么了吗?

多谢,

答案1

保持简单。文件名可通过以下方式轻松获取\view

\documentclass{beamer}
\usepackage{pgffor}

\begin{document}

\foreach \view in {example-image-a,example-image-b,example-image-c}{
  \begin{frame}
    \frametitle{MY TITLE 1}
    \framesubtitle{My subtitle 1}
    \begin{figure}
      \includegraphics[width=\textwidth]{\view}
    \end{figure}
  \end{frame}
}

\end{document}

答案2

列表中的项目listofitems一旦读取,即可完全展开。包提供列表循环。

\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usepackage{listofitems}
\begin{document}
\def\views{example-image-a,example-image-b,example-image-c}
\readlist*\filenames{\views}
\foreachitem \view \in \filenames[]
{
  \begin{frame}
    \frametitle{MY TITLE 1}
    \framesubtitle{My subtitle \viewcnt}
    n = \viewcnt{}
    Filename = \view
    \begin{figure}
      \centering
      \includegraphics[width=\textwidth]{\view}
    \end{figure}
  \end{frame}
}
\end{document}

在此处输入图片描述

相关内容