Nunjucks Templating Guide
Nunjucks Templating Guide
Documentation
Getting Started (getting-started.html)
Templating (templating.html)
API (api.html)
FAQ (faq.html)
Templates
https://mozilla.github.io/nunjucks/templating.html#math 1/38
3/20/2020 Nunjucks
joiner([separator])
Builtin Filters
abs
batch
capitalize
center
default(value, default, [boolean])
dictsort
dump
escape (aliased as e)
first
float
forceescape
groupby
indent
int
join
last
length
list
lower
nl2br
random
rejectattr (only the single-argument form)
replace
reverse
round
safe
selectattr (only the single-argument form)
slice
sort(arr, reverse, caseSens, attr)
string
striptags (value, [preserve_linebreaks])
sum
title
trim
truncate
upper
urlencode
urlize
wordcount
Templating
English (/nunjucks/templating.html) 中文 (/nunjucks/cn/templating.html)
Français (/nunjucks/fr/templating.html)
This is an overview of the templating features available in Nunjucks.
https://mozilla.github.io/nunjucks/templating.html#math 2/38
3/20/2020 Nunjucks
File Extensions
Although you are free to use any file extension you wish for your Nunjucks template files, the
Nunjucks community has adopted .njk .
If you are developing tools or editor syntax helpers for Nunjucks, please include recognition
of the .njk extension.
Syntax Highlighting
Plugins are available in various editors to support the jinja syntax highlighting of
Nunjucks.
atom https://github.com/alohaas/language-nunjucks
(https://github.com/alohaas/language-nunjucks)
vim https://github.com/niftylettuce/vim-jinja (https://github.com/niftylettuce/vim-jinja)
brackets https://github.com/axelboc/nunjucks-brackets
(https://github.com/axelboc/nunjucks-brackets)
sublime https://github.com/mogga/sublime-
nunjucks/blob/master/Nunjucks.tmLanguage (https://github.com/mogga/sublime-
nunjucks/blob/master/Nunjucks.tmLanguage)
emacs http://web-mode.org (http://web-mode.org)
vscode https://github.com/ronnidc/vscode-nunjucks
(https://github.com/ronnidc/vscode-nunjucks)
Variables
https://mozilla.github.io/nunjucks/templating.html#math 3/38
3/20/2020 Nunjucks
A variable looks up a value from the template context. If you wanted to simply display a
variable, you would do:
{{ 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.
{{ 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.
{{ 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, and you can add your own (api#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.
https://mozilla.github.io/nunjucks/templating.html#math 4/38
3/20/2020 Nunjucks
{% 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>
{% extends "parent.html" %}
{% block left %}
This is the left side!
{% endblock %}
{% block right %}
This is the right side!
{% endblock %}
<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. This variable
can contain a string that points to a template file, or it can contain a compiled Template
object that has been added to the context. That way you can dynamically change which
template is inherited when rendering by setting it in the context.
{% extends parentTemplate %}
https://mozilla.github.io/nunjucks/templating.html#math 5/38
3/20/2020 Nunjucks
You leverage inheritance with the extends and 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:
{% block right %}
{{ super() }}
Right side!
{% endblock %}
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.
{% 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 (or elseif , which is simply an alias of
elif ) and else :
https://mozilla.github.io/nunjucks/templating.html#math 6/38
3/20/2020 Nunjucks
{% if hungry %}
I am hungry
{% elif tired %}
I am tired
{% else %}
I am good!
{% endif %}
for
for iterates over arrays and dictionaries.
If you are using a custom template loader that is asynchronous, see asyncEach )
<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.
var food = {
'ketchup': '5 tbsp',
'mustard': '1 tbsp',
'pickle': '0 tbsp'
};
https://mozilla.github.io/nunjucks/templating.html#math 7/38
3/20/2020 Nunjucks
ES iterators are supported, like the new builtin Map and Set. But also anything implementing
the iterable protocol.
{% for x, y, z in points %}
Point: {{ x }}, {{ y }}, {{ z }}
{% endfor %}
asyncEach
asyncEach is an asynchronous version of for . You only need this if you are using a
custom template loader that is asynchronous; otherwise you will never need it. Async filters
and extensions also need this, but internally loops are automatically converted into
asyncEach if any async filters and extensions are used within the loop.
https://mozilla.github.io/nunjucks/templating.html#math 8/38
3/20/2020 Nunjucks
asyncEach has exactly the same behavior of for , but it enables asynchronous control of
the loop. The reason those tags are separate is performance; most people use templates
synchronously and it's much faster for for to compile to a straight JavaScript for loop.
At compile-time, Nunjucks is not aware how templates are loaded so it's unable to determine
if an include block is asynchronous or not. That's why it can't automatically convert loops
for you, and you must use asyncEach for iteration if you are loading templates
asynchronously inside the loop.
// If you are using a custom loader that is async, you need asyncEach
var env = new nunjucks.Environment(AsyncLoaderFromDatabase, opts);
<h1>Posts</h1>
<ul>
{% asyncEach item in items %}
{% include "item-template.html" %}
{% endeach %}
</ul>
asyncAll
asyncAll is similar to asyncEach , except it renders all the items in parallel, preserving the
order of the items. This is only helpful if you are using asynchronous filters, extensions, or
loaders. Otherwise you should never use this.
Let's say you created a filter named lookup that fetches some text from a database. You
could then render multiple items in parallel with asyncAll :
<h1>Posts</h1>
<ul>
{% asyncAll item in items %}
<li>{{ item.id | lookup }}</li>
{% endall %}
</ul>
If lookup is an asynchronous filter, it's probably doing something slow like fetching
something from disk. asyncAll allows you reduce the time it would take to execute the loop
sequentially by doing all the async work in parallel, and the template rendering resumes
once all the items are done.
https://mozilla.github.io/nunjucks/templating.html#math 9/38
3/20/2020 Nunjucks
macro
macro allows you to define reusable chunks of content. It is similar to a function in a
programming language. Here's an example:
{{ field('user') }}
{{ field('pass', type='password') }}
Keyword/default arguments are available. See keyword arguments for a more detailed
explanation.
You can import macros from other templates, allowing you to reuse them freely across your
project.
Important note: If you are using the asynchronous API, please be aware that you cannot
do anything asynchronous inside macros. This is because macros are called like normal
functions. In the future we may have a way to call a function asynchronously. If you do this
now, the behavior is undefined.
set
set lets you create/modify a variable.
{{ username }}
{% set username = "joe" %}
{{ username }}
You can introduce new variables, and also set multiple at once:
{% set x, y, z = 5 %}
https://mozilla.github.io/nunjucks/templating.html#math 10/38
3/20/2020 Nunjucks
If set is used at the top-level, it changes the value of the global template context. If used
inside scoped blocks like an include or a macro, it only modifies the current scope.
It is also possible to capture the contents of a block into a variable using block assignments.
The syntax is similar to the standard set , except that the = is omitted, and everything until
the {% endset %} is captured.
{% set standardModal %}
{% include 'standardModalData.html' %}
{% endset %}
extends
extends is used to specify template inheritance. The specified template is used as a base
template. See Template Inheritance.
{% extends "base.html" %}
You can store the template to inherit in a variable and use it by omitting quotes. This variable
can contain a string that points to a template file, or it can contain a compiled Template
object that has been added to the context. That way you can dynamically change which
template is inherited when rendering by setting it in the context.
{% extends parentTemplate %}
In fact, extends accepts any arbitrary expression, so you can pass anything into it, as long
as that expression evaluates to a string or a compiled Template object:
block
block defines a section on the template and identifies it with a name. This is used by
template inheritance. Base templates can specify blocks and child templates can override
them with new content. See Template Inheritance.
https://mozilla.github.io/nunjucks/templating.html#math 11/38
3/20/2020 Nunjucks
{% block css %}
<link rel="stylesheet" href="app.css" />
{% endblock %}
Child templates can override the item block and change how it is displayed:
{% extends "item.html" %}
{% block item %}
The name of the item is: {{ item.name }}
{% endblock %}
A special function super is available within blocks which will render the parent block's
content. See super.
include
include pulls in other templates in place. It's useful when you need to share smaller
chunks across several templates that already inherit other templates.
{% include "item.html" %}
This is especially useful for cutting up templates into pieces so that the browser-side
environment can render the small chunks when it needs to change the page.
include actually accepts any arbitrary expression, so you can pass anything into it, as long
as the expression evaluates to a string or a compiled Template object:
{% include name + ".html" %} .
It might be useful to not throw an error if a template does not exist. Use the
ignore missing option to suppress such errors.
https://mozilla.github.io/nunjucks/templating.html#math 12/38
3/20/2020 Nunjucks
Included templates can themselves extend another template (so you could have a set of
related includes that all inherit a common structure). An included template does not
participate in the block structure of its including template; it has a totally separate inheritance
tree and block namespace. In other words, an include is not a pre-processor that pulls the
included template code into the including template before rendering; instead, it fires off a
separate render of the included template, and the results of that render are included.
import
import loads a different template and allows you to access its exported values. Macros and
top-level assignments (done with set ) are exported from templates, allowing you to access
them in a different template.
Imported templates are processed without the current context, so they do not have access to
any of the current template variables.
Let's start with a template called forms.html that has the following in it:
{% macro label(text) %}
<div>
<label>{{ text }}</label>
</div>
{% endmacro %}
We can import this template and bind all of its exported values to a variable so that we can
use it:
{{ forms.label('Username') }}
{{ forms.field('user') }}
{{ forms.label('Password') }}
{{ forms.field('pass', type='password') }}
You can also import specific values from a template into the current namespace with
from import :
https://mozilla.github.io/nunjucks/templating.html#math 13/38
3/20/2020 Nunjucks
{{ description('Username') }}
{{ field('user') }}
{{ description('Password') }}
{{ field('pass', type='password') }}
import actually accepts any arbitrary expression, so you can pass anything into it, as long
as the expression evaluates to a string or a compiled Template object:
{% import name + ".html" as obj %} .
raw
If you want to output any of the special Nunjucks tags like {{ , you can use a {{ , you can
use a {% raw %} block and anything inside of it will be output as plain text.
verbatim
{% verbatim %} has identical behavior as {% raw %} . It is added for compatibility with
the Twig verbatim tag (http://twig.sensiolabs.org/doc/tags/verbatim.html).
filter
A filter block allows you to call a filter with the contents of the block. Instead passing a
value with the | syntax, the render contents from the block will be passed.
{% filter title %}
may the force be with you
{% endfilter %}
call
A call block enables you to call a macro with all the text inside the tag. This is helpful if
you want to pass a lot of content into a macro. The content is available inside the macro as
caller() .
https://mozilla.github.io/nunjucks/templating.html#math 14/38
3/20/2020 Nunjucks
{% macro add(x, y) %}
{{ caller() }}: {{ x + y }}
{% endmacro%}
Keyword Arguments
jinja2 uses Python's keyword arguments support to allow keyword arguments in functions,
filters, and macros. Nunjucks supports keyword arguments as well by introducing a new
calling convention.
bar and baz are keyword arguments. Nunjucks converts them into a hash and passes it
as the last argument. It's equivalent to this call in javascript:
Since this is a standard calling convention, it works for all functions and filters if they are
written to expect them. Read more (api#Keyword-Arguments) about this in the API section.
Macros allow you to also use keyword arguments in the definition, which allows you to
specify default values. Nunjucks automatically maps the keyword arguments to the ones
defined with the macro.
{{ foo(1, 2) }} -> 1, 2, 5, 6
{{ foo(1, 2, w=10) }} -> 1, 2, 5, 10
You can mix positional and keyword arguments with macros. For example, you can specify a
positional argument as a keyword argument:
https://mozilla.github.io/nunjucks/templating.html#math 15/38
3/20/2020 Nunjucks
You can also simply pass a positional argument in place of a keyword argument:
{{ foo(5, 6, 7, 8) }} -> 5, 6, 7, 8
Comments
You can write comments using {# and #} . Comments are completely stripped out when
rendering.
Whitespace Control
Normally the template engine outputs everything outside of variable and tag blocks verbatim,
with all the whitespace as it is in the file. Occasionally you don't want the extra whitespace,
but you still want to format the template cleanly, which requires whitespace.
You can tell the engine to strip all leading or trailing whitespace by adding a minus sign ( - )
to the start or end block or a variable.
The exact output of the above would be "12345". The {%- strips the whitespace right before
the tag, and -%} the strips the whitespace right after the tag.
And the same is for variables: {{- will strip the whitespace before the variable, and -}}
will strip the whitespace after the variable.
Expressions
You can use many types of literal expressions that you are used to in javascript.
https://mozilla.github.io/nunjucks/templating.html#math 16/38
3/20/2020 Nunjucks
Math
Nunjucks allows you to operate on values (though it should be used sparingly, as most of
your logic should be in code). The following operators are available:
Addition: +
Subtraction: -
Division: /
Division and integer truncation: //
Division remainder: %
Multiplication: *
Power: **
{{ 2 + 3 }} (outputs 5)
{{ 10/5 }} (outputs 2)
{{ numItems*2 }}
Comparisons
==
===
!=
!==
>
>=
<
<=
Examples:
Logic
and
or
not
Use parentheses to group expressions
https://mozilla.github.io/nunjucks/templating.html#math 17/38
3/20/2020 Nunjucks
Examples:
If Expression
Similar to javascript's ternary operator, you can use if as if it were an inline expression:
The above outputs the string "true" if foo is truthy, otherwise "false". This is especially useful
for default values like so:
{{ "true" if foo }}
Function Calls
If you have passed a javascript method to your template, you can call it like normal.
{{ foo(1, 2, 3) }}
Regular Expressions
A regular expression can be created just like JavaScript, but needs to be prefixed with r :
https://mozilla.github.io/nunjucks/templating.html#math 18/38
3/20/2020 Nunjucks
g : apply globally
i : case insensitive
m : multiline
y : sticky
Autoescaping
If autoescaping is turned on in the environment, all output will automatically be escaped for
safe output. To manually mark output as safe, use the safe filter. Nunjucks will not escape
this output.
{{ foo }} // <span%gt;
{{ foo | safe }} // <span>
If autoescaping is turned off, all output will be rendered as it is. You can manually escape
variables with the escape filter.
{{ foo }} // <span>
{{ foo | escape }} // <span>
Global Functions
There are a few builtin global functions that cover some common cases.
https://mozilla.github.io/nunjucks/templating.html#math 19/38
3/20/2020 Nunjucks
In the above example, odd rows have the class "odd" and even rows have the class "even".
You can access the current item on the current property (in the above example,
cls.current ).
joiner([separator])
When combining multiple items, it's common to want to delimit them with something like a
comma, but you don't want to output the separator for the first item. The joiner class will
output separator (default ",") whenever it is called except for the first time.
If tags was ["food", "beer", "dessert"] , the above example would output
food, beer, dessert .
Builtin Filters
Nunjucks has ported most of jinja's filters (http://jinja.pocoo.org/docs/dev/templates/#builtin-
filters), and has a few of its own:
abs
Return the absolute value of the argument:
Input
{{ -3|abs }}
Output
batch
https://mozilla.github.io/nunjucks/templating.html#math 20/38
3/20/2020 Nunjucks
Input
Output
12-34-56
capitalize
Make the first letter uppercase, the rest lower case:
Input
Output
This is a test
center
Center the value in a field of a given width:
Input
{{ "fooo" | center }}
Output
fooo
https://mozilla.github.io/nunjucks/templating.html#math 21/38
3/20/2020 Nunjucks
If value is strictly undefined , return default , otherwise value . If boolean is true, any
JavaScript falsy value will return default (false, "", etc)
In version 2.0, this filter changed the default behavior of this filter. Previously, it acted
as if boolean was true by default, and any falsy value would return default . In 2.0
the default is only an undefined value returns default . You can get the old behavior
by passing true to boolean , or just use value or default .
dictsort
Sort a dict and yield (key, value) pairs:
{% set items = {
'e': 1,
'd': 2,
'c': 3,
'a': 4,
'f': 5,
'b': 6
} %}
{% for item in items | dictsort %}
{{ item[0] }}
{% endfor %}
Output
a b c d e f
dump
Call JSON.stringify
(https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
on an object and dump the result into the template. Useful for debugging:
{{ items | dump }} .
Input
https://mozilla.github.io/nunjucks/templating.html#math 22/38
3/20/2020 Nunjucks
Output
["a",1,{"b":true}]
Dump provides the spaces parameter to add spaces or tabs to the resulting values. This
makes the results more readable.
Input
Output
[
"a",
1,
{
"b": true
}
]
Input
Output
[
"a",
1,
{
"b": true
}
]
escape (aliased as e)
Convert the characters &, <, >, ‘, and ” in strings to HTML-safe sequences. Use this if you
need to display text that might contain such characters in HTML. Marks return value as
markup string
https://mozilla.github.io/nunjucks/templating.html#math 23/38
3/20/2020 Nunjucks
Input
{{ "<html>" | escape }}
Output
<html>
first
Get the first item in an array or the first letter if it's a string:
Input
Output
float
Convert a value into a floating point number. If the conversion fails 0.0 is returned. This
default can be overridden by using the first parameter.
Input
{{ "3.5" | float }}
Output
3.5
forceescape
https://mozilla.github.io/nunjucks/templating.html#math 24/38
3/20/2020 Nunjucks
groupby
Group a sequence of objects by a common attribute:
Input
{% set items = [
{ name: 'james', type: 'green' },
{ name: 'john', type: 'blue' },
{ name: 'jim', type: 'blue' },
{ name: 'jessie', type: 'green' }
]
%}
Output
indent
Indent a string using spaces. Default behaviour is not to indent the first line. Default
indentation is 4 spaces.
Input
{{ "one\ntwo\nthree" | indent }}
Output
one
two
three
https://mozilla.github.io/nunjucks/templating.html#math 25/38
3/20/2020 Nunjucks
Input
{{ "one\ntwo\nthree" | indent(6) }}
Output
one
two
three
Input
Output
one
two
three
int
Convert the value into an integer. If the conversion fails 0 is returned.
Input
{{ "3.5" | int }}
Output
join
Return a string which is the concatenation of the strings in a sequence:
Input
https://mozilla.github.io/nunjucks/templating.html#math 26/38
3/20/2020 Nunjucks
Output
123
The separator between elements is an empty string by default which can be defined with an
optional parameter:
Input
Output
foo,bar,bear
Input
{% set items = [
{ name: 'foo' },
{ name: 'bar' },
{ name: 'bear' }]
%}
Output
foo,bar,bear
last
Get the last item in an array or the last letter if it's a string:
Input
https://mozilla.github.io/nunjucks/templating.html#math 27/38
3/20/2020 Nunjucks
Output
length
Return the length of an array or string, or the number of keys in an object:
Input
{{ [1,2,3] | length }}
{{ "test" | length }}
{{ {key: value} | length }}
Output
3
4
1
list
Convert the value into a list. If it was a string the returned list will be a list of characters.
Input
Output
f,o,o,b,a,r,
https://mozilla.github.io/nunjucks/templating.html#math 28/38
3/20/2020 Nunjucks
lower
Convert string to all lower case:
Input
{{ "fOObAr" | lower }}
Output
foobar
nl2br
Replace new lines with <br /> HTML elements:
Input
Output
foo<br />\nbar
random
Select a random value from an array. (This will change everytime the page is refreshed).
Input
{{ [1,2,3,4,5,6,7,8,9] | random }}
Output
https://mozilla.github.io/nunjucks/templating.html#math 29/38
3/20/2020 Nunjucks
Input
Output
replace
Replace one item with another. The first item is the item to be replaced, the second item is
the replaced value.
Input
Output
123.56
Insert a replaced item before and after a value, by adding quote marks and replacing them
surrounding an item:
Input
Output
.a.a.a.b.b.b.c.c.c.
https://mozilla.github.io/nunjucks/templating.html#math 30/38
3/20/2020 Nunjucks
Input
Note in this instance the required quote marks surrounding the list.
Output
xxabbbccc
Input
Output
aaxbbccc
reverse
Reverse a string:
Input
{{ "abcdef" | reverse }}
Output
fedcba
Reverse an array:
Input
https://mozilla.github.io/nunjucks/templating.html#math 31/38
3/20/2020 Nunjucks
Output
4 3 2 1
round
Round a number:
Input
{{ 4.5 | round }}
Output
Input
{{ 4 | round(0, "floor") }}
Output
Input
{{ 4.12346 | round(4) }}
Output
4.1235
https://mozilla.github.io/nunjucks/templating.html#math 32/38
3/20/2020 Nunjucks
safe
Mark the value as safe which means that in an environment with automatic escaping
enabled this variable will not be escaped.
Input
Output
Input
Output
slice
Slice an iterator and return a list of lists containing those items:
Input
https://mozilla.github.io/nunjucks/templating.html#math 33/38
3/20/2020 Nunjucks
<div class="columwrapper">
{%- for items in arr | slice(3) %}
<ul class="column-{{ loop.index }}">
{%- for item in items %}
<li>{{ item }}</li>
{%- endfor %}
</ul>
{%- endfor %}
</div>
Output
<div class="columwrapper">
<ul class="column-1">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="column-2">
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul class="column-3">
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>
string
Convert an object to a string:
Input
https://mozilla.github.io/nunjucks/templating.html#math 34/38
3/20/2020 Nunjucks
Output
1,2,3,4,
sum
Output the sum of items in the array:
Input
Output
title
Make the first letter of the string uppercase:
Input
Output
https://mozilla.github.io/nunjucks/templating.html#math 35/38
3/20/2020 Nunjucks
trim
Strip leading and trailing whitespace:
Input
Output
foo
truncate
Return a truncated copy of the string. The length is specified with the first parameter which
defaults to 255. If the second parameter is true the filter will cut the text at length. Otherwise
it will discard the last word. If the text was in fact truncated it will append an ellipsis sign
("..."). A different ellipsis sign than "(...)" can be specified using the third parameter.
Truncate to 3 characters:
Input
Output
foo(...)
Input
Output
https://mozilla.github.io/nunjucks/templating.html#math 36/38
3/20/2020 Nunjucks
foo ba ?
upper
Convert the string to upper case:
Input
{{ "foo" | upper }}
Output
FOO
urlencode
Escape strings for use in URLs, using UTF-8 encoding. Accepts both dictionaries and regular
strings as well as pairwise iterables.
Input
{{ "&" | urlencode }}
Output
%26
urlize
Convert URLs in plain text into clickable links:
Input
Output
https://mozilla.github.io/nunjucks/templating.html#math 37/38
3/20/2020 Nunjucks
Input
Output
<a href="http://mozilla.github.io/">http://moz</a>
wordcount
Count and output the number of words in a string:
Input
Output
https://mozilla.github.io/nunjucks/templating.html#math 38/38