<commit_before>---
layout: subpage
title: Templates
---
{% raw %}

# Templating

This is an overview of the templating features available in nunjucks.

> Nunjucks is essentially a port of
> [jinja2](http://jinja.pocoo.org/docs/), so you can read their
> [docs](http://jinja.pocoo.org/docs/templates/) if you find anything
> lacking here. Read about the differences
> [here](http://mozilla.github.io/nunjucks/faq.html#can-i-use-the-same-templates-between-nunjucks-and-jinja2-what-are-the-differences).

## Variables

A variable looks up a value from the template context. If you wanted
to simply display a variable, you would do:

```jinja
{{ username }}
```

This looks up `username` from the context and displays it. Variable
names can have dots in them which lookup properties, just like
javascript. You can also use the square bracket syntax.

```jinja
{{ foo.bar }}
{{ foo["bar"] }}
```

These two forms to the exact same thing, just like javascript.

If a value is `undefined` or `null`, nothing is displayed. The same
behavior occurs when referencing undefined or null objects. The
following all output nothing if `foo` is undefined: `{{ foo }}`, `{{
foo.bar }}`, `{{ foo.bar.baz }}`.

## Filters

Filters are essentially functions that can be applied to variables.
They are called with a pipe operator (`|`) and can take arguments.

```jinja
{{ foo | title }}
{{ foo | join(",") }}
{{ foo | replace("foo", "bar") | capitalize }}
```

The third example shows how you can chain filters. It would display
"Bar", by first replacing "foo" with "bar" and then capitalizing it.

Nunjucks comes with several
[builtin filters](#builtin-filters), and you can
[add your own](api#Registering-custom-filters) as well.

## Template Inheritance

Template inheritance is a way to make it easy to reuse templates. When
writing a template, you can define "blocks" that child templates can
override. The inheritance chain can be as long as you like.

If we have a template `parent.html` that looks like this:

```jinja
{% block header %}
This is the default content
{% endblock %}

<section class="left">
  {% block left %}{% endblock %}
</section>

<section class="right">
  {% block right %}
  This is more content
  {% endblock %}
</section>
```

And we render this template:

```jinja
{% extends "parent.html" %}

{% block left %}
This is the left side!
{% endblock %}

{% block right %}
This is the right side!
{% endblock %}
```

The output would be:

```jinja
This is the default content

<section class="left">
  This is the left side!
</section>

<section class="right">
  This is the right side!
</section>  
```

You can store the template to inherit in a variable and use it by
omitting quotes. That way you can dynamically change which template is
inherited when rendering by setting it in the context.

```jinja
{% extends parentTemplate %}
```

You leverage inheritance with the [`extends`](#extends) and
[`block`](#block) tags. A more detailed explanation of inheritance can
be found in the [jinja2
docs](http://jinja.pocoo.org/docs/templates/#template-inheritance).

### super

You can render the contents of the parent block inside a child block
by calling `super`. If in the child template from above you had:

```jinja
{% block right %}
{{ super() }}
Right side!
{% endblock %}
```

The output of the block would be:

```
This is more content
Right side!
```

## Tags

Tags are special blocks that perform operations on sections of the
template. Nunjucks comes with several builtin, but [you can add your own](api.html#custom-tags).

### if

`if` tests a condition and lets you selectively display content. It behaves exactly as javascript's `if` behaves.

```jinja
{% if variable %}
  It is true
{% 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`:

```jinja
{% if hungry %}
  I am hungry
{% elif tired %}
  I am tired
{% else %}
  I am good!
{% endif %}
```

You can also use if as an [inline expression](#if-expression).

### for

`for` iterates over arrays and dictionaries.

> If you are using a custom template loader that is asynchronous, see
> [`asyncEach`](#asynceach))

```js
var items = [{ title: "foo", id: 1 }, { title: "bar", id: 2}];
```

```jinja
<h1>Posts</h1>
<ul>
{% for item in items %}
  <li>{{ item.title }}</li>
{% endfor %}
</ul>
```

The above example lists all the posts using the `title` attribute of each item in the `items` array as the display value.

You can also iterate over objects/hashes:

```js
var food = {
  'ketchup': '5 tbsp',
  'mustard': '1 tbsp',
  'pickle': '0 tbsp'
};
```

```jinja
{% for ingredient, amount in food %}
  Use {{ amount }} of {{ ingredient }}
{% endfor %}
```

The [`dictsort`](http://jinja.pocoo.org/docs/templates/#dictsort) filter is available for sorting objects when iterating over them (*new in 0.1.8*).

Additionally, nunjucks will unpack arrays into variables (*new in 0.1.8*):

```js
var points = [[0, 1, 2], [5, 6, 7], [12, 13, 14]];
```

```jinja<commit_msg>Document use of 'else' in 'for' tags<commit_after>---
layout: subpage
title: Templates
---
{% raw %}

# Templating

This is an overview of the templating features available in nunjucks.

> Nunjucks is essentially a port of
> [jinja2](http://jinja.pocoo.org/docs/), so you can read their
> [docs](http://jinja.pocoo.org/docs/templates/) if you find anything
> lacking here. Read about the differences
> [here](http://mozilla.github.io/nunjucks/faq.html#can-i-use-the-same-templates-between-nunjucks-and-jinja2-what-are-the-differences).

## Variables

A variable looks up a value from the template context. If you wanted
to simply display a variable, you would do:

```jinja
{{ username }}
```

This looks up `username` from the context and displays it. Variable
names can have dots in them which lookup properties, just like
javascript. You can also use the square bracket syntax.

```jinja
{{ foo.bar }}
{{ foo["bar"] }}
```

These two forms to the exact same thing, just like javascript.

If a value is `undefined` or `null`, nothing is displayed. The same
behavior occurs when referencing undefined or null objects. The
following all output nothing if `foo` is undefined: `{{ foo }}`, `{{
foo.bar }}`, `{{ foo.bar.baz }}`.

## Filters

Filters are essentially functions that can be applied to variables.
They are called with a pipe operator (`|`) and can take arguments.

```jinja
{{ foo | title }}
{{ foo | join(",") }}
{{ foo | replace("foo", "bar") | capitalize }}
```

The third example shows how you can chain filters. It would display
"Bar", by first replacing "foo" with "bar" and then capitalizing it.

Nunjucks comes with several
[builtin filters](#builtin-filters), and you can
[add your own](api#Registering-custom-filters) as well.

## Template Inheritance

Template inheritance is a way to make it easy to reuse templates. When
writing a template, you can define "blocks" that child templates can
override. The inheritance chain can be as long as you like.

If we have a template `parent.html` that looks like this:

```jinja
{% block header %}
This is the default content
{% endblock %}

<section class="left">
  {% block left %}{% endblock %}
</section>

<section class="right">
  {% block right %}
  This is more content
  {% endblock %}
</section>
```

And we render this template:

```jinja
{% extends "parent.html" %}

{% block left %}
This is the left side!
{% endblock %}

{% block right %}
This is the right side!
{% endblock %}
```

The output would be:

```jinja
This is the default content

<section class="left">
  This is the left side!
</section>

<section class="right">
  This is the right side!
</section>  
```

You can store the template to inherit in a variable and use it by
omitting quotes. That way you can dynamically change which template is
inherited when rendering by setting it in the context.

```jinja
{% extends parentTemplate %}
```

You leverage inheritance with the [`extends`](#extends) and
[`block`](#block) tags. A more detailed explanation of inheritance can
be found in the [jinja2
docs](http://jinja.pocoo.org/docs/templates/#template-inheritance).

### super

You can render the contents of the parent block inside a child block
by calling `super`. If in the child template from above you had:

```jinja
{% block right %}
{{ super() }}
Right side!
{% endblock %}
```

The output of the block would be:

```
This is more content
Right side!
```

## Tags

Tags are special blocks that perform operations on sections of the
template. Nunjucks comes with several builtin, but [you can add your own](api.html#custom-tags).

### if

`if` tests a condition and lets you selectively display content. It behaves exactly as javascript's `if` behaves.

```jinja
{% if variable %}
  It is true
{% 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`:

```jinja
{% if hungry %}
  I am hungry
{% elif tired %}
  I am tired
{% else %}
  I am good!
{% endif %}
```

You can also use if as an [inline expression](#if-expression).

### for

`for` iterates over arrays and dictionaries.

> If you are using a custom template loader that is asynchronous, see
> [`asyncEach`](#asynceach))

```js
var items = [{ title: "foo", id: 1 }, { title: "bar", id: 2}];
```

```jinja
<h1>Posts</h1>
<ul>
{% for item in items %}
  <li>{{ item.title }}</li>
{% else %}
  <li>This would display if the 'item' collection were empty</li>
{% endfor %}
</ul>
```

The above example lists all the posts using the `title` attribute of each item in the `items` array as the display value. If the `items` array were empty, the contents of the optional `else` clause would instead be rendered.

You can also iterate over objects/hashes:

```js
var food = {
  'ketchup': '5 tbsp',
  'mustard': '1 tbsp',
  'pickle': '0 tbsp'
};
```

```jinja
{% for ingredient, amount in food %}
  Use {{ amount }} of {{ ingredient }}
{% endfor %}
```

The [`dictsort`](http://jinja.pocoo.org/docs/templates/#dictsort) filter is available for sorting objects when iterating over them (*new in 0.1.8*).

Additionally, nunjucks will unpack arrays into variables (*new in 0.1.8*):

```js
var points = [[0, 1, 2], [5, 6, 7], [12, 13, 14]];
```

```jinja
{'fraction_non_alphanumeric': 0.13294015276032098, 'fraction_numerical': 0.005414289857874891, 'mean_word_length': 4.105626850937808, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1411675', 'n_tokens_mistral': 3417, 'n_tokens_neox': 3094, 'n_words': 1374}