Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandoc template: different separator for last item

Tags:

I'm writing a custom Pandoc template and want it to print a list of authors so that all authors are separated with ", " except for the last author who instead is separated with an "and". Can this be done?

Let's say this is my template:

$if(title)$
$title$
$endif$
$if(author)$
$for(author)$$author$$sep$, $endfor$
$endif$
$body$

Which outputs:

My title
Author 1, Author 2, Author 3
Document body

But I want it to output:

My title
Author 1, Author 2 and Author 3
Document body
like image 414
Fredrik Savje Avatar asked Feb 20 '17 21:02

Fredrik Savje


1 Answers

You have to use so-called "pipes" from Pandoc template syntax (see https://pandoc.org/MANUAL.html).

We'll make a for loop for all-but-last items in our array (it is considered as a pronoun inside the loop, refering to the values from authors/allbutlast). For those elements of our authors array, we'll use ", " as a separator, but outside the loop, we'll simply put the "final separator" ("and" in this case), and the last element of authors array (~ stands for unbreakable space, if you are going to output to LaTeX).

$for(authors/allbutlast)$$it$$sep$, $endfor$ and~$authors/last$

EDIT: In case there's only one author, use something like this:

$if(author/allbutlast)$
$for (author/allbutlast)$
${it}$sep$, 
$endfor$
and ${author/last}
$else$
${author/last}
$endif$
like image 104
Jan Netík Avatar answered Sep 25 '22 10:09

Jan Netík