Nunjucks
lastmod 2024-03-20created 2024-03-156 edits
Pros
In terms of performance, pug renders faster than nunjucks, but pug requires converting html tags into pug syntax separately, whereas Nunjucks can borrow html syntax as is, so it has good compatibility.
Basic syntax
Nunjucks variables
Just wrap them with {{ and }}. (e.g. <h1>{{title}}</h1>)
Note that since the content is substituted as is, you should not write it like
this; even though {{name}} itself is the value, you must quote it with double quotes (") like
this.
Variable declaration
Loops
Write for in inside {% %}. To use the index number, use loop.index. At the end of the for loop, enter { % endfor % } to mark where the for loop ends.
How to escape
Use | safe after the string.
Conditionals
A single line also works:
Logical operators
Use English words instead of symbols.
-
&&->and -
||->or -
!->not
Example:
Modularization
include - you can use include to insert another HTML file.
extends & block
Use extends to define a layout.
IntelliJ integration
There is no officially supported tool. (Checked 2024-03-20) Instead, try the Twig plugin. See IntelliJ IDEA#Integrating Nunjucks files using Twig for details.
List of web template system
- Web template system (template)
- Handlebars
- Liquid (Jekyll)
- Mustache
- EJS (Embedded JavaScript templates)
- Nunjucks (JavaScript)
- Jinja/Jinja2 (Python)
- Jade
- pug
- Twig (PHP)