4

I want to set the fill-color of a rectangle depending on a number stored in a counter. This is my try:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\background}[1]{%
\begin{tikzpicture}[overlay,remember picture]
\fill [#1]
        ($ (current page.north west) + (.7cm,-.7cm) $)
        rectangle
        ($ (current page.south east) + (-.7cm,.7cm) $);
\end{tikzpicture}
}

\newcounter{test}
\setcounter{test}{1}
\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

\begin{document}
\background{green} % everything is good
\newpage
\background{\chooseColor} % throwing the error shown below
\end{document}

Whilst \background{green} yields what I'm looking for, \background{\chooseColor} throws the following Error:

! Package pgfkeys Error: I do not know the key '/tikz/green ' and I am going to
 ignore it. Perhaps you misspelled it. 

I conclude from the error, that \background{\chooseColor} has been evaluated to 'green' correctly, however I get that error message. Is there anything I missed out on this one? I will be glad for every help!

1
  • 1
    Welcome to TeX.SE!
    – Mensch
    Mar 22, 2021 at 11:05

2 Answers 2

9

The error comes from the fact that you define

\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

Hence, you assign \chooseColor with green or red with a trailing space. This space is taken over to TikZ, but green (with a space) is not a valid color to TikZ (nor is red ).

Remove the spaces and it should work:

\newcommand{\chooseColor}{\ifnum\thetest=1 green\else red\fi}
2
  • 1
    This is totally not a beginner's mistake by the way! It happens to me all the time =) Mar 22, 2021 at 11:25
  • 1
    Thank you very much, sometimes the answer is both too tricky and simple at the same time!
    – Niklas
    Mar 23, 2021 at 13:24
4

Another way to remove the spaces is to use the /.expanded key handler.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcommand{\background}[1]{%
\begin{tikzpicture}[overlay,remember picture]
\fill [#1]
        ($ (current page.north west) + (.7cm,-.7cm) $)
        rectangle
        ($ (current page.south east) + (-.7cm,.7cm) $);
\end{tikzpicture}
}

\newcounter{test}
\setcounter{test}{1}
\newcommand{\chooseColor}{\ifnum\thetest=1 green \else red \fi}

\begin{document}
\background{green} % everything is good
\newpage
\background{color/.expanded=\chooseColor} % throwing the error shown below
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .