Introduction
Nunjucks is a full-featured templating engine for JavaScript, created by Mozilla and inspired by Python's Jinja2. It supports template inheritance, macros, filters, and async rendering, making it suitable for both server-side HTML generation and browser-side template rendering.
What Nunjucks Does
- Renders templates with variables, loops, conditionals, and filters
- Supports template inheritance with block overrides for layout reuse
- Provides macros for reusable template components with parameters
- Handles asynchronous data sources through async filters and extensions
- Auto-escapes output by default to prevent cross-site scripting
Architecture Overview
Nunjucks compiles template strings into an intermediate AST, then generates optimized JavaScript render functions. A configurable loader system resolves template names from the filesystem (Node.js) or precompiled bundles (browser). The runtime maintains a context stack for variable scoping and supports synchronous and asynchronous rendering modes through the same template API.
Self-Hosting & Configuration
- Install via npm for Node.js or precompile templates for the browser
- Call nunjucks.configure() with a template directory and options like autoescape
- Use nunjucks.render(name, context) for synchronous or callback-based rendering
- Precompile templates with the nunjucks-precompile CLI for client-side use
- Register custom filters and extensions for domain-specific template logic
Key Features
- Jinja2-compatible syntax familiar to Python developers
- Template inheritance with extendable blocks for consistent layouts
- Macros and imports for reusable template components across files
- Async-capable rendering for templates that need to fetch data
- Built-in auto-escaping with safe filter for trusted content
Comparison with Similar Tools
- Handlebars — simpler logic-less syntax with helpers; no template inheritance or macros
- EJS — embeds raw JavaScript in templates; more flexible but less structured
- Mustache.js — minimal logic-less templates; no filters, inheritance, or async support
- Pug — indentation-based HTML syntax; different authoring style and tighter HTML coupling
FAQ
Q: Can Nunjucks run in the browser? A: Yes, precompile your templates and include the slim runtime bundle for client-side rendering.
Q: Is Nunjucks compatible with Jinja2 templates? A: Mostly yes. Core syntax is the same, but some Python-specific filters and behaviors differ.
Q: Does Nunjucks support streaming output? A: No, it renders the full output as a string. For streaming, consider rendering in chunks manually.
Q: How do I add custom filters? A: Call env.addFilter(name, function) on a configured environment to register filters globally.