# latex/tikz macro conditional

I'm writing a latex macro which includes a tikz drawing, now I'd like to draw one path only if the optional parameter is set.

How can you interact from within tikz with the parameters given from latex?

something like this:

\newcommand{\myTikzDrawing}[1][default]{
\begin{tikzpicture}
\draw (0,1) -- (1,1);
\draw (0,0) -- (1,0); %this line should only be drawn, if #1 is set to the default value
\end{tikzpicture}
}


You can use the is if key to introduce a conditional.

\documentclass{article}
\usepackage{tikz}
\newif\ifTikZdrawthis
\tikzset{draw this/.is if=TikZdrawthis,draw this/.default=true}
\newcommand{\myTikzDrawing}[1][draw this=true]{
\begin{tikzpicture}[#1]
\draw (0,1) -- (1,1);
\ifTikZdrawthis
\draw (0,0) -- (1,0); %this line should only be drawn, if #1 is set to the default value
\fi
\end{tikzpicture}
}
\begin{document}
\myTikzDrawing
\bigskip

\myTikzDrawing[blue]
\bigskip

\myTikzDrawing[red,draw this]
\end{document}


• Looks good, would you just be so kind to show the dependency between the naming (I'm not quite sure, what has to have the same name and what you've just chosen to name the same ;) May 16, 2020 at 23:46
• @atticus The /.is if key handler is described on p. 989 of pgfmanual v3.1.5. The naming is such that skip the if in the beginning, i.e. draw this/.is if=TikZdrawthis links the Boolean draw this to the TeX \if \ifTikZdrawthis. There is also the /.is choice key handler, which allows you to go beyond Boolean yes/no choices.
– user194703
May 17, 2020 at 2:03
• Why is the second line not drawn in that case, when you pass only the option blue along? Don't you set with draw this/.default=true the key to a default value of true, so if the key is not set, it should be true by default? May 17, 2020 at 12:49
• @atticus I thought this is what you are asking for. The reason is that the if is set to false. The command is such that if you do not specify the optional argument, it will be draw this=true per the LaTeX mechanism \newcommand{\myTikzDrawing}[1][draw this=true]{..... That is, if you say \myTikzDrawing[blue], you do not say draw this=true . If you want the opposite behavior, just set the initial value of draw this to true.
– user194703
May 17, 2020 at 13:08
• @atticus You asked: "Why is the second line not drawn in that case, when you pass only the option blue along? Don't you set with draw this/.default=true the key to a default value of true, so if the key is not set, it should be true by default? " Be aware that the default is applied only when the key is used without providing a value. If the key is not used at all, then the default is not applied. And \newif initializes the \if..-switch to \iffalse. So if the key draw this is not applied at all, then \ifTikZdrawthis is \iffalse. May 18, 2020 at 7:18