# addtocontentsline only if not empty

I'm using a macro, which does this:

\addcontentsline{toc}{section}{\string\iffoo bla \string\fi}


When compiled normally, foo is false, so the line should not appear in the toc. But when the .toc file is included in some other script, I set foo to true in that script and the same .toc file should also show the bla.

If I use the code as above, I'll get

\contentsline {section}{\iffoo bla \fi }{1}{section.0.1}


which does print an ..... line without any text when foo is false. What I probably do need is this:

\iffoo \contentsline {section}{bla}{1}{section.0.1} \fi


How do I get this?

• \addtocontents or \addcontentsline... but not \addtocontentsline (at least I don't know that macro). Please provide an MWE to make this question clearer – user31729 May 4 '15 at 20:38
• \string\iffoo\ bla\string\fi would be better. In addition, I think, that \iffoo \addcontentsline{....} \fi is actually the correct thing you want to have – user31729 May 4 '15 at 20:43

Since the content line should be there only \iffoo expands to true, it's no use to do the test inside of the 3rd argument of \addcontentsline, since this will start the \contentsline machine in the .aux file, leading to an .toc entry anyway.

To prevent this, the test must be outside of \addcontentsline. See the two different behaviours in the example below. The two 'empty' lines are the result of the testing within \addcontentsline -- this is not wanted, I am pretty sure.

\documentclass{article}

\usepackage{blindtext}
\newif\iffoo

\foofalse
\begin{document}
\tableofcontents

\clearpage

\section{First}
\blindtext

\addcontentsline{toc}{section}{\string\iffoo\ Will be in the toc or empty \string\fi}

\iffoo
\addcontentsline{toc}{section}{Will be in the toc only if foo is true}

\fi

\section{another one}
\footrue

\addcontentsline{toc}{section}{\string\iffoo\ Will not appear  in the toc but the page number will be there  \string\fi}

\iffoo
\addcontentsline{toc}{section}{Will be in the toc only if foo is true too}
\fi

\end{document}
`