[Tex/LaTex] If, elseif and else conditionals in the preamble

conditionalspreamble

I have a scenario where I need to define a few commands and environments based on some condition in the preamble. I used to use \newtoggle, set the conditional using \toggletrue or \togglefalse and use \iftoggle macros defined in the etoolbox package. However, the conditionals that I have now are not bound by the boolean type. It conforms to the below if-else structure

if <condition 1>
    define commands <a1, a2>
    define environments <b1, b2>
elseif <condition 2>
    define commands <a3, a4>
    define environments <b3, b4>
.. 
else
    define commands <p, q>
    define environments <x, y>

I tried using the algorithmic package, but apparently, I cannot make use of that in the preamble. Is there any way I could define multi-conditional if-else cases in the preamble?.

Update 1 The command and environment names in the different cases will be the same, just the definition will be different

Update 2 The conditions are multiple toggles. I plan to use the \newtoggle commands to define the conditional variables.

\newtoggle{variable1}
\toggletrue{variable1}
\newtoggle{variable2}
\togglefalse{variable2}

The pseudo code for the conditionals are as follows

% The conditions
if variable1 && variable2
    % do something
else if variable1 && !variable2
    % do something else
else if !variable1 && variable2
    % do the thing
else 
    % do the other thing

I know this can be done using nested if-conditionals, but I was wondering if there are any non-nested ways to do it.

Best Answer

As in almost any programming language, \if... statements can be nested, however, there's no \elseif, so \else \if.... has to be used and concluded with \fi.

A new \if... variable (well, macro actually) can be defined with

\newif\ifsomename

which is initially set to the false state. \somenametrue will set to true, \somenamefalse will set it false.

Nested \if...\fi can be very tedious, in TeX, however.

Here's some pseudo-code

\ifsomething...
 do this and that
\else
\ifsomethingother
...
\else
\ifsomethingmore
\fi
\fi
\fi

The following small example should print 'Foo that' with bold font, since \dothattrue was specified.

\documentclass{article}


\newif\ifdothis

\newif\ifdothat

\dothattrue  % Setting the state of the boolean variable \ifdothat` to true, otherwise it's false already (or use \dothatfalse explicitly)

\ifdothis

\newcommand{\foo}{\textbf{Foo}}
\else
\ifdothat
\newcommand{\foo}{\textbf{Foo that}}
\else
\newcommand{\foo}{\textbf{Dummy content}}
\fi % \fi of \ifdothat
\fi % Outer \fi


\begin{document}
\foo

\end{document}
Related Question