Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

95 lines (69 sloc) 2.519 kB

Nunjucks

I’m tired of the lack of good templating systems for large js apps. The biggest missing feature between all of them is template inheritance, something necessary for a non-trivial site. Other problems is the ugliness of embedding javascript, too much logic in templates, etc.

I hope that Nunjucks can be better. It is heavily jinja2 inspired because I think it is a great solution for templating. Nunjucks does not claim to be a direct port of jinja2, but most things will work the same in both projects.

Installation

npm install nunjucks

Using

Here is an example template that works with the current code:

{# base.html #}
<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>

---

{# index.html, inherits base.html #}
{% extends "base.html" %}

{% block content %}

{# Variables and filters #}
Hello {{ name|title }}!

{# Call a function #}
{{ messages() }}

{# Conditionals #}    
{% if sick %}
  no
{% elif throwing %}
  THROWING UP?!
{% elif pooping %}
  STOP POOPING
{% else %}
  GOOD!
{% endif %}

{# For iteration #}
<p>
  Let's print some numbers:
  <ul>
  {% for i in [1,2,3,4,5] %}
   <li>{{ i }}</li>
  {% endfor %}
  </ul>
</p>

{% endblock %}

To compile templates, you can create a Template directly or load one from an environment object. Right now the environment just loads the template from the disk relative to the current location.

var nunjucks = require('nunjucks');
var tmpl = new nunjucks.Template('Hello {{ username }}');
console.log(tmpl.render({ username: "james" }));

// From an environment
var env = new nunjucks.Environment();
var tmpl = env.getTemplate('test.html');
console.log(tmpl.render({ username: "james" }));

Express

To integrate with express, do the following (this will change before the first release):

var nunjucks = require('nunjucks');
var loaders = nunjucks.loaders;
var express = require('express');

var env = new nunjucks.Environment(new loaders.FileSystemLoader('templates'));
env.express(app);

Status

This is very close to a 0.1 beta release. It is mostly feature-complete with all the basic stuff ported from Jinja. There are a few things left:

  • Implement the “include” tag
  • Allow referencing: {{ foo.bar }} and {{ foo[“bar”] }}
  • Better express integration
  • Make template loading asynchronous (requires different generated code too)
  • Support precompiled templates
  • Implement caching
  • Write more tests, fix bugs
Jump to Line
Something went wrong with that request. Please try again.