Templating

This is an overview of the templating features available in GitBook. GitBook uses the Nunjucks and Jinja2 syntax.

Escaping

If you want to output any of the special templating tags, you can use raw and anything inside of it will be output as plain text.

  1. {% raw %}
  2. this will {{ not be processed }}
  3. {% endraw %}

Variables

A variable looks up a value from the book context.

Variables are defined in the book.json file:

  1. {
  2. "variables": {
  3. "myVariable": "Hello World"
  4. }
  5. }

Display Variables

Variables specified in the book.json are accessible under the scope book:

  1. {{ book.myVariable }}

This looks up myVariable from the book variables and displays it. Variable names can have dots in them which lookup properties. You can also use the square bracket syntax.

  1. {{ book.foo.bar }}
  2. {{ book["bar"] }}

If a value is undefined, nothing is displayed. The following all output nothing if foo is undefined: {{ foo }}, {{ foo.bar }}, {{ foo.bar.baz }}.

Context variables

Some variables are also available to get informations about the current file or the GitBook instance:

Name Description
file.path Path of the file relative to the book
file.mtime Last modified date of the file

Tags

Tags are special blocks that perform operations on sections of the template.

If

if tests a condition and lets you selectively display content. It behaves exactly as a programming language’s if behaves.

  1. {% if variable %}
  2. It is true
  3. {% endif %}

If variable is defined and evaluates to true, “It is true” will be displayed. Otherwise, nothing will be.

You can specify alternate conditions with elif and else:

  1. {% if hungry %}
  2. I am hungry
  3. {% elif tired %}
  4. I am tired
  5. {% else %}
  6. I am good!
  7. {% endif %}

for

for iterates over arrays and dictionaries.

Let’s consider your variables in the book.json:

  1. {
  2. "variables": {
  3. "authors": [
  4. { "name": "Samy" },
  5. { "name": "Aaron" }
  6. ]
  7. }
  8. }
  1. # Authors
  2. {% for author in book.authors %}
  3. - {{ author.name }}
  4. {% endfor %}

The above example lists all the authors using the name attribute of each item in the authors array as the display value.

include

Include is detailed in the Content References article.