4.3 Templates

When Pandoc converts Markdown to another output format, it uses a template under the hood. The template is a plain-text file that contains some variables of the form $variable$. These variables will be replaced by their values generated by Pandoc. Below is a very brief template for HTML output:

It has two variables title and body. The value of title comes from the title field of the YAML metadata, and body is the HTML code generated from the body of the Markdown input document. For example, suppose we have a Markdown document:

If we use the above template to generate an HTML document, its source code will be like this:

The actual HTML, LaTeX, and EPUB templates are more complicated, but the idea is the same. You need to know what variables are available: some variables are built-in Pandoc variables, and some can be either defined by users in the YAML metadata, or passed from the command-line option -V or --variable. Some variables only make sense in specific output formats, e.g., the documentclass variable is only used in LaTeX output. Please see the documentation of Pandoc to learn more about these variables, and you can find all default Pandoc templates in the GitHub repository https://github.com/jgm/pandoc-templates.

Note that for HTML output, bookdown requires some additional comment tokens in the template, and we have explained them in Section 3.1.2.