Skip to content
Search

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

<input name="name" value={{name}} />

this; even though {{name}} itself is the value, you must quote it with double quotes (") like

<input name="name" value="{{name}}" />

this.

Variable declaration

{% set 자바스크립트 구문 %}

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

{% if VARIABLE %}

{% elif %}

{% else %}

{% endif %}

A single line also works:

<h1>{{ '참' if true else '거짓' }}</h1>

Logical operators

Use English words instead of symbols.

  • && -> and
  • || -> or
  • ! -> not

Example:

{% if happy and hungry %} 
    I am happy *and* hungry; both are true. 
{% endif %} 

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

See also

Favorite site

author Zer0 sitemap