4

I want to import a picture by passing a variable which stores its name instead of the name itself. Here is example code

\documentclass{article}
\usepackage[margin=0.7in]{geometry}
\usepackage[parfill]{parskip}
\usepackage[utf8]{inputenc}

\usepackage{xparse} \usepackage{tikz}

\begin{document} \ExplSyntaxOn

\newcommand{\varpicture}{ \tl_new:N \l_img_name_tl \tl_set:Nn \l_img_name_tl {uniquename.png} \node (p) at (0,0) { \includegraphics[width=100pt]{uniquename.png} %works \includegraphics[width=100pt]{\tl_use:N \l_img_name_tl} %doesn't work };
}

\ExplSyntaxOff

\begin{tikzpicture} \varpicture \end{tikzpicture} \end{document}

Only resource that I found regarding this issue is here: How to use variable for \includegraphics and \attachfile in LaTeX3

If I try to rename the file such that it is called: "uniquename" instead of "uniquename.png" I get the same error, which is that the file cannot be found. None of the solutions used in the other thread work for me.

I compile TeX code with "pdflatex".

1 Answers1

6

A macro at the start of the file name would be expanded once in \includegraphics (as stated by @HeikoOberdiek).

A tl variable can be expected to expand to its contents in one expansion step, so you can drop the \tl_use:N (which needs more than one step) at the beginning and directly use \l_img_name_tl. On recent installations the variant with \tl_use:N would work as well (as also mentioned by @UlrikeFischer)

\documentclass{article}
\usepackage[margin=0.7in]{geometry}
\usepackage[parfill]{parskip}
\usepackage[utf8]{inputenc}

\usepackage{xparse} \usepackage{tikz}

\begin{document} \ExplSyntaxOn

\tl_new:N \l_img_name_tl

\newcommand{\varpicture}{ \tl_set:Nn \l_img_name_tl {example-image-duck.pdf} \node (p) at (0,0) { \includegraphics[width=100pt]{example-image-duck.pdf} %works \includegraphics[width=100pt]{\l_img_name_tl} };
}

\ExplSyntaxOff

\begin{tikzpicture} \varpicture \end{tikzpicture} \end{document}

enter image description here

Skillmon
  • 60,462