iftoggle with minted

I have a problem with the minted package in combination with etoolbox's iftoggle. It should be related (or basically be the same error) to this beamer question: minted environment in frame causes error but the there stated solution (using a fragile frame) cannot be applied in this way to a standard document.

The following MWE gives an error when \toggletrue{test}:

\documentclass{report}%
\usepackage{etoolbox}
\newtoggle{test}
\toggletrue{test}
\usepackage{minted}
\begin{document}
\iftoggle{test}{
\begin{minted}
test
\end{minted}
}{}
test
\end{document}


The error is

(./mwe.aux)
(/usr/local/texlive/2016/texmf-dist/tex/context/base/mkii/supp-pdf.mkii
)
! Missing \endcsname inserted.
\def
l.15 }
{}


How can I fix this problem?

• \iftoggle{<toggle>}{<true>}{<false>} expects a <toggle>, yet you supply it with something else. That's the problem. What is it that you're really after?
– Werner
Nov 8 '18 at 22:13
• This will not work because the \iftoggle grabs the verbatim environment as argument, which will make it not work. Nov 8 '18 at 22:15
• @Werner: sorry that was a typo in the mwe, I fixed it. Nov 9 '18 at 9:18

You can't have a minted environment in the argument to another command.

For this special case, you can do

\iftoggle{test}{\iftrue}{\iffalse}
\begin{minted}
test
\end{minted}
\fi


Full example

\documentclass{report}
\usepackage{minted}
\usepackage{etoolbox}
\newtoggle{test}
\toggletrue{test}

\begin{document}
\iftoggle{test}{\iftrue}{\iffalse}
\begin{minted}{text}
test
\end{minted}
\fi

test

\togglefalse{test}
\iftoggle{test}{\iftrue}{\iffalse}
\begin{minted}{text}
test
\end{minted}
\fi

test

\end{document}