[Tex/LaTex] Passing image path to \includegraphics using a macro

graphicsmacros

I'm trying to use a single environment for a number of different cases. For each case, I need the environment to have a different image associated with it.

When I try this, I get

! LaTeX Error: File `image1.png' not found.

An example illustrates what I'm trying to do:

\documentclass{memoir}

\usepackage{graphicx}

\newcommand{\ImageOne}{image1.png}
\newcommand{\ImageTwo}{image2.png}
\newcommand{\currentimage}{}

\newcommand{\MyFigure}{%
\begin{figure}
\centering
\includegraphics[width=0.5\linewidth]{\currentimage}
\end{figure}}

\begin{document}

\renewcommand{\currentimage}{\ImageOne}
\MyFigure

\renewcommand{\currentimage}{\ImageTwo}
\MyFigure

\end{document}

Best Answer

Apparently \includegraphics does only one step of expansion for its argument, so you end up with \includegraphics[width=0.5\linewidth]{\ImageOne} and this is not what TeX expects.

Use \let instead of \renewcommand:

\documentclass{memoir}

\usepackage{graphicx}

\newcommand{\ImageOne}{image1.png}
\newcommand{\ImageTwo}{image2.png}

\newcommand{\MyFigure}{%
  \begin{figure}
  \centering
  \includegraphics[width=0.5\linewidth]{\currentimage}
  \end{figure}}

\begin{document}

\let\currentimage\ImageOne
\MyFigure

\let\currentimage\ImageTwo
\MyFigure

\end{document}

However, I don't think this is a good way to go.

Related Question