Getting Started

When Using Node...

$ npm install nunjucks

Once installed, simply use require('nunjucks') to load it.

When in the Browser...

Grab nunjucks.js (min) for the full library, or nunjucks-slim.js (min) for the slim version which only works with precompiled templates.

Which file should you use?

Simply include nunjucks with a script tag on the page:

<script src="nunjucks.js"></script>

or load it as an AMD module:

define(['nunjucks'], function(nunjucks) {
});

Whatever you do, make sure to precompile your templates in production! There are grunt and gulp tasks to help with that. Read more about optimal client-side configurations in Browser Usage.

Usage

This is the simplest way to use nunjucks. First, set any configuration flags (i.e. autoescaping) and then render a string:

nunjucks.configure({ autoescape: true });
nunjucks.renderString('Hello {{ username }}', { username: 'James' });

You usually won't use renderString, instead you should write templates in individual files and use render. That way you can inherit and include templates. In this case, you need to tell nunjucks where these files live with the first argument of configure:

nunjucks.configure('views', { autoescape: true });
nunjucks.render('index.html', { foo: 'bar' });

In node, 'views' would be a path relative to the current working directory. In the browser, it would be a relative URL, and you probably want it to be absolute, like '/views'.

Using express? Simply pass your express app into configure:

var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

app.get('/', function(req, res) {
    res.render('index.html');
});

The above API works in node and in the browser (express is only in node, obviously). In node, nunjucks loads templates from the filesystem by default, and in the browser loads them over HTTP.

If you precompiled your templates in the browser, they will automatically be picked up by the system and nothing more has to be changed. This makes it easy to use the same code in development and production, while using precompiled templates in production.

More Information

That's only the tip of the iceberg. See API for API docs and Templating about the templating language.