[Tex/LaTex] etoolbox’s iftoggle vs verbatim

conditionalsetoolboxverbatim

My problem is that I can set up toggles, using etoolbox's \newtoggle{x}, set it to true with \toggletrue{x} and even use it with iftoggle{x}{this for true}{this for false}. However, if I try to put a verbatim environment inside a conditional block, it breaks and gives me an error message:

Runaway argument?
 for x in range(1, 43): print('x=', x) \end {verbatim} 
./q4.tex:19: Paragraph ended before \@xverbatim was complete.
<to be read again> )
./Quiz1.tex:90: Missing number, treated as zero.
<to be read again> 
                   {
l.90 \vspace{
             1 pc} 
? 
                   \par 
l.19 }{}

?

for the code:

\iftoggle{displaysolutions}{

\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
    print('x=', x)
\end{verbatim}

}{}

Any ideas of what I'm possibly doing wrong? Any alternatives?

Best Answer

Having a verbatim environment in the argument to another command is not allowed: the changes that need to be done to the special characters' meaning can't be made when the environment has already been read in as an argument.

A way out is adapting to use a "primitive" syntax:

\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\newcommand{\iftoggleverb}[1]{%
  \ifcsdef{etb@tgl@#1}
    {\csname etb@tgl@#1\endcsname\iftrue\iffalse}
    {\etb@noglobal\etb@err@notoggle{#1}\iffalse}%
}
\makeatother

\newtoggle{displaysolutions}
\togglefalse{displaysolutions}

\begin{document}
\section{A}

Are solutions displayed? \iftoggle{displaysolutions}{Yes}{No}.

\iftoggleverb{displaysolutions}

\noindent\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
    print('x=', x)
\end{verbatim}

\fi


\toggletrue{displaysolutions}

\section{B}

Are solutions displayed? \iftoggle{displaysolutions}{Yes}{No}.

\iftoggleverb{displaysolutions}

\noindent\textit{The statement will execute y times.}
\begin{verbatim}
for x in range(0, y):
    print('x=', x)
\end{verbatim}

\fi

\end{document}

There should be a "matching \fi" after the part you want displayed or not.

You can also use

\iftoggleverb{displaysolutions}
<material to be displayed if the toggle is true>
\else
<material to be displayed if the toggle is false>
\fi

enter image description here

Important limitation. Don't use \iftoggleverb nested in other conditional statements.

Related Question