Friday, October 3, 2014

Conditionally Processing LaTeX Documents

Sometimes one may wish to process a LaTeX document based on a condition. For instance, one may wish to conditional process a resume written in LaTeX depending where she is sending the document, i.e., she may wish to expand certain sections, shrink certain sections, or exclude certain sections, in which way, she does not need to maintain multiple different documents that share significant amount of content.

We can use LaTex ifthen package to achieve the purpose. An example is given in this post.

However, some (this and this) suggests that the package is obsolete and we should use the etoolbox package.

I have two examples that use the ifthen package and the etoolbox package, respectively. The complete examples are in Github. I tested the examples on a Linux machine.

In the first example, we use  the etoolbox package and create a "toggle" file (toggle.tex) in the Makefile

ex_cond_1_long.pdf: ex_cond_1.tex
 [ ! -f toggle.tex ] || rm -f toggle.tex
 echo "\\\\toggletrue{long}" > toggle.tex
 pdflatex -jobname ex_cond_1_long ex_cond_1.tex
 
ex_cond_1_short.pdf: ex_cond_1.tex
 [ ! -f toggle.tex ] || rm -f toggle.tex
 echo "\\\\togglefalse{long}" > toggle.tex
 pdflatex -jobname ex_cond_1_short ex_cond_1.tex

The content of toggle.tex is now either,

\toggletrue{long}
or

\togglefalse{long}
Then, in the LaTex file (ex_cond_1.tex), one of two files (long.tex or short.tex) will be conditionally included,

\documentclass[11pt, letterpaper]{article}
\usepackage{etoolbox}
\newtoggle{long}

\input{toggle.tex}

\iftoggle{long}{
    \input{long.tex}
}{
    \input{short.tex}
}

The second example uses the ifthen packag. We demonstrate that we can pass a value from the command line using jobname as shown in the Makefile,

ex_cond_2_long.pdf: ex_cond_2.tex
 pdflatex -jobname ex_cond_2_long ex_cond_2.tex

ex_cond_2_short.pdf: ex_cond_2.tex
 pdflatex -jobname ex_cond_2_short ex_cond_2.tex

Based on whether the jobname is ex_cond_2_long or ex_cond_2_short, one of two files (long.tex or short.tex) will be conditionally included,

\ifthenelse{\equal{\detokenize{ex_cond_2_long}}{\jobname}}{
    \input{long.tex}
}{
    \input{short.tex}
}




1 comment: