作者:Yihui Xie
译者:郑宝童
日期:2021.06.01


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:

当Pandoc将Markdown转换为另一种输出格式时,它使用了一个模板。模板是一个纯文本文件,其中包含一些形式为$variable$的变量。这些变量将被Pandoc生成的值替换。下面是一个非常简短的HTML输出模板:

  1. <html>
  2. <head>
  3. <title>$title$</title>
  4. </head>
  5. <body>
  6. $body$
  7. </body>
  8. </html>

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:

它有两个变量titlebodytitle的值来自YAML元数据的title字段,body是Markdown输入文档的正文生成的HTML代码。例如,假设我们有一个Markdown文档:

  1. ---
  2. title: A Nice Book
  3. ---
  4. # Introduction
  5. This is a **nice** book!

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

如果我们使用上面的模板来生成一个HTML文档,它的源代码是这样的:

  1. <html>
  2. <head>
  3. <title>A Nice Book</title>
  4. </head>
  5. <body>
  6. <h1>Introduction</h1>
  7. <p>This is a <strong>nice</strong> book!</p>
  8. </body>
  9. </html>

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.

实际的HTML、LaTeX和EPUB模板更加复杂,但其思想是相同的。您需要知道哪些变量可用:有些变量是内置的Pandoc变量,有些变量是可以由用户在YAML元数据中定义,或者从命令行选项-V or --variable传递。有些变量只在特定的输出格式中有意义,例如documentclass变量只在LaTeX输出中使用。请参阅Pandoc文档以了解更多关于这些变量的信息,你可以在GitHub仓库 https://github.com/jgm/pandoc-templates中找到所有默认的Pandoc模板

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

注意,对于HTML输出,bookdown需要在模板中添加一些注释标记,我们已经在 3.1.2节中解释了它们。