Search code examples
pandoc

Boolean Operator in Pandoc Template


Pandoc Template supports if-clauses and for-loops. For example,

$if(foo)$
part one
$else$
part two
$endif$

How to do boolean logic inside the if-clause argument? For example,

$if(foo AND bar)$
both
$endif$

and

$if(foo OR bar)$
both
$endif$

Solution

  • The template language has no support for this. Boolean AND can be simulated by using two ifs.

    $-- foo AND bar
    $if(foo)$
    $if(bar)$
    both
    $endif$
    $endif$
    

    Boolean OR is not really possible though; the best method would be to use a partial to avoid too much repetition:

    $-- foo OR bar
    $if(foo)$
    $my.partial()$
    $else$
    $if(bar)$
    $my.partial()$
    $endif$
    $endif$
    

    It is often easier to move the calculations to a (Lua) filter for even mildly complicated logic.

    function Meta (meta)
      meta['foo-and-bar'] = meta.foo or meta.bar
      return meta
    end
    

    Drawback: if foo or bar are not part of the metadata but of the set of variables, then this won't work, as filters don't have access to variables. Use a custom writer in that case.