Nunjucks Documentation
Nunjucks is a powerful templating engine for JavaScript that allows you to create dynamic content using variables, filters, and control structures.
Available Context
In this environment, you have access to the following context object:
{
params: {}, // Query parameters
table: { // Contains all available tables
tableExample: [], // Each table is a list of objects
anotherTable: []
}
}
Basic Syntax
Variables
Access variables using double curly braces:
{{ params.name }}
{{ table.tableExample[0].id }}
Conditionals
{% if params.showDetails %}
Showing details for {{ params.id }}
{% else %}
No details available
{% endif %}
Loops
<ul>
{% for row in table.tableExample %}
<li>{{ row.name }}: {{ row.value }}</li>
{% endfor %}
</ul>
Filters
Modify variables with filters using the pipe symbol:
{{ params.name | upper }}
{{ params.date | date("YYYY-MM-DD") }}
{{ table.tableExample[0].amount | round(2) }}
Common filters:
upper
,lower
: Change casetrim
: Remove whitespacefirst
,last
: Get first/last itemlength
: Get length of array/stringsort
: Sort an arrayjoin
: Join array elements
Expressions
{{ table.tableExample[0].price * 1.1 }}
{{ "Price: " + table.tableExample[0].price }}
{{ table.tableExample.length > 0 ? "Has items" : "Empty" }}
Comments
{# This is a comment that won't be rendered #}
Practical Examples
Formatting a table:
<table>
<thead>
<tr>
{% for key in Object.keys(table.tableExample[0]) %}
<th>{{ key }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for row in table.tableExample %}
<tr>
{% for key in Object.keys(table.tableExample[0]) %}
<td>{{ row[key] }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Conditional formatting:
{% for item in table.tableExample %}
<div class="{% if item.value > 100 %}highlight{% endif %}">
{{ item.name }}: {{ item.value }}
</div>
{% endfor %}
Using params for filtering:
{% if params.filter %}
<h3>Filtered results for: {{ params.filter }}</h3>
{% set filteredRows = table.tableExample | filter(row => row.category == params.filter) %}
{% for row in filteredRows %}
<div>{{ row.name }}</div>
{% endfor %}
{% else %}
<h3>All results</h3>
{% for row in table.tableExample %}
<div>{{ row.name }}</div>
{% endfor %}
{% endif %}
Accessing multiple tables:
<div>
<h3>Table 1: {{ table.tableExample.length }} rows</h3>
<ul>
{% for row in table.tableExample %}
<li>{{ row.name }}</li>
{% endfor %}
</ul>
{% if table.anotherTable %}
<h3>Table 2: {{ table.anotherTable.length }} rows</h3>
<ul>
{% for row in table.anotherTable %}
<li>{{ row.title }}</li>
{% endfor %}
</ul>
{% endif %}
</div>
Aggregating data:
{% set total = 0 %}
{% for item in table.tableExample %}
{% set total = total + item.amount %}
{% endfor %}
<div>Total: {{ total }}</div>
For more information, visit the Nunjucks documentation.
Last updated