你曾经一直在寻觅的 JavaScript 模板引擎就在这里!
  • 功能丰富且强大,并支持块级继承(block inheritance)、自动转义、宏(macro)、异步控制等等。完美继承了 jinja2 的衣钵。
  • 快速 & 干练 并且高效。运行时代码经过压缩之后只有 8K 大小, 可在浏览器端执行预编译模板。
  • 可扩展 性超强,用户可以自定义过滤器(filter)和扩展模块。
  • 到处 可运行,无论是 node 还是任何浏览器都支持,并且还可以预编译模板。
{% extends "base.html" %}

{% block header %}
<h1>{{ title }}</h1>
{% endblock %}

{% block content %}
<ul>
  {% for name, item in items %}
  <li>{{ name }}: {{ item }}</li>
  {% endfor %}
</ul>
{% endblock %}
      

谁在用 Nunjucks ?

Firefox Marketplace

“Nunjucks has allowed us to port all of our existing templates from a Django project to something that's easier to manage. By moving our templates to the client, transfer sizes are reduced and page responsiveness increases significantly. Our API supplies data, meaning we can decouple testing the front-end from testing the back-end. Nunjucks has made our app feel native.”

– Matt Basta, Firefox Marketplace team

Mozilla Webmaker

Webmaker from the Mozilla Foundation encourages people to create. Using web technologies, you can create visually rich media with a powerful real-time tool. Using nunjucks, it was easy to collaborate on the templates and implement complex features such as localization. There haven't been any problems with performance or stability.

Backbeam

“Backbeam provides tools for mobile and web development. When we were planning the web developing features we needed an easy-to-use yet powerful templating engine. But almost all JavaScript templating engines lacked of important features such as template inheritance or flexibility to add custom behaviours (e.g. custom filters). Then we just saw the announcement of nunjucks on James' website. Since that moment we knew that nunjucks would be THE choice. Now we use nunjucks in many parts of our product. Users can edit HTML and email templates using nunjucks right in their browsers. We are really happy with our choice :)”

– Alberto Gimeno, founder of backbeam.io

Apostrophe CMS

“P'unk Avenue chose Nunjucks as the template language for the Apostrophe content management system, an open source CMS for node developers. We chose Nunjucks because of its close relationship with the Jinja and Twig languages, and also for its test coverage and robust implementation.”

– Tom Boutell, Senior Developer at P'unk Avenue

And many, many more...

更多实例

内置了大量过滤器(filter)可供直接使用,对变量进行处理,也可以开发自己专属功能。
{{ foo | title }}
{{ foo | join(",") }}
{{ foo | replace("foo", "bar") | capitalize }}
可以对任何函数或过滤器(filter)使用 关键字参数(keyword arguments)
{{ foo(1, 2, bar=3, baz=4) }}
{{ bar | transform(level=2) }}
模板继承 能让你以更强大的方式复用模板。通过定义父模板的基本结构然后由子模板来填充内容。
{% extends "base.html" %}

{% block header %}
<h3>{{ subtitle }}</h3>
{% endblock %}

{% block content %}
<h1>{{ page.title }}</h1>
<p>{{ page.content }}</p>
{% endblock %}
如果你需要在过滤器中调用异步函数,你甚至还可以编写 异步模板!充分利用 asyncAll 从而让所有循环并行执行, 假定 lookup 过滤器是异步执行的。
<h1>Posts</h1>
<ul>
{% asyncAll item in items %}
  <li>{{ item.id | lookup }}</li>
{% endall %}
</ul>

这只是开胃菜而已。请查看 中问文档 了解所有强大特性!