NAME

Text::Nunjucks - Nunjucks templating engine, ported 1:1 from the JavaScript original

VERSION

version 0.001

SYNOPSIS

use strict;
use warnings;
use Text::Nunjucks::Environment;

my $env = Text::Nunjucks::Environment->new( [], { trimBlocks => 1 } );

print $env->render_string(
  "Hello {{ name | title }}\n"
    . "{% for item in items %}\n"
    . "- {{ item | upper }}\n"
    . "{% endfor %}",
  { name => 'world', items => [ 'a', 'b<c' ] },
);

This prints

Hello World
- A
- B&lt;C

DESCRIPTION

Text::Nunjucks is a 1:1 Perl port of Nunjucks v3.2.4 (https://mozilla.github.io/nunjucks/), Mozilla's templating engine for JavaScript: the same template, the same context and the same options give the same output, byte for byte, and the same error messages as the JavaScript original. Autoescaping is on by default, as in Nunjucks. The template language is Nunjucks' own, so its documentation applies as it stands: see https://mozilla.github.io/nunjucks/templating.html for the tags, the built-in filters, the is tests and the global functions (range, cycler, joiner). A deliberate difference from upstream is a recorded decision; any other difference is a bug.

This module is the distribution's front page and loads no code of its own. The engine is used through Text::Nunjucks::Environment: construct an Environment with the loaders and options you want, register your own filters, tests and globals on it, and render with render (a template looked up through a loader) or render_string (a template given as a string). Template context is a plain hash reference. A Perl undef is the template's undefined and the object Text::Nunjucks::Runtime->None is its null.

The public classes

Text::Nunjucks::Environment

The engine's entry point: loaders, options, filters, tests, globals, extensions, render, render_string and get_template. Loading it also loads Text::Nunjucks::Template (a compiled template, the object get_template returns and the one that does the rendering) and Text::Nunjucks::Context (the per-render bookkeeping, used by the engine and not meant for callers).

Text::Nunjucks::Loader

The base class a template loader extends, and the contract a custom loader fulfils.

Text::Nunjucks::Loader::FileSystem

Loads templates from directories on disk.

Text::Nunjucks::Loader::Precompiled

Serves templates from a hash of already compiled template objects.

Text::Nunjucks::EmitterObj

The on / emit role loaders and the Environment share.

Text::Nunjucks::Lib::TemplateError and Text::Nunjucks::Lib::Error

The error objects a failed render throws or passes to its callback.

The remaining modules (Text::Nunjucks::Lexer, Text::Nunjucks::Parser, Text::Nunjucks::Nodes, Text::Nunjucks::Transformer, Text::Nunjucks::Compiler, Text::Nunjucks::Runtime, Text::Nunjucks::Lib, Text::Nunjucks::Filters, Text::Nunjucks::Tests and Text::Nunjucks::Globals) are the engine itself, each a port of the upstream file of the same name. They are documented for orientation only and are not a stable interface.

STATUS

This is release 0.001. The entry point is Text::Nunjucks::Environment: construct one with Text::Nunjucks::Environment->new($loaders, \%opts) and call render, render_string or get_template on it. Perl 5.40 or newer is required. Paths follow the POSIX model of node's path; Windows paths come later (see "DIFFERENCES FROM NUNJUCKS").

Not in 0.001. The top-level API of Nunjucks' index.js (the package-level configure, reset, compile, render and render_string over a default environment) does not exist: Text::Nunjucks loads no code and has no functions or class methods. Its Perl calling convention is undecided. Also not ported: jinja-compat, precompile and its CLI, NodeResolveLoader, WebLoader, chokidar watch (a truthy watch dies with watch requires chokidar to be installed, ADR 0018), the browser bundles (ADR 0022), express-app.js (upstream's Environment#express(app), also reached by nunjucks.configure({ express: app }); Text::Nunjucks::Environment has no express method) and precompile-global.js (the wrapper that emits JavaScript source for precompile; the Perl format of a precompiled template is open). The Perl shape of an extension object (add_extension) is not settled.

DIFFERENCES FROM NUNJUCKS

Same template, same context, same options give the same bytes and the same error message, except for what is listed here. The decisions are in docs/adr/ (https://github.com/Getty/p5-text-nunjucks/tree/main/docs/adr); ADR NNNN names one, kNN is an open card on the project board for a divergence that has not been decided or fixed yet.

Decided differences

Values and kinds (ADR 0001, 0006, 0007)

A value's kind comes from the Perl scalar itself: a number you built as a number is a number, a numeric string is a string, so "1" and 1 behave as in JavaScript. Data from a JSON module arrives right; build values with 0+$x or "$x" when in doubt. A Perl undef is the template's undefined; null is the singleton Text::Nunjucks::Runtime->None (a JSON null in the context is turned into it). Numbers are printed as JavaScript prints them.

Object key order (ADR 0011)

Dicts written in a template keep their insertion order. A plain Perl hash passed in the context has no order, so it iterates sorted by key. Use Hash::Ordered for an order you control; Tie::IxHash is not honoured.

Strings are UTF-16 (ADR 0012)

String operations count in UTF-16 code units, as JavaScript does. Templates, context and results are decoded character strings, and loaders decode UTF-8.

Native methods (ADR 0008)

Only a curated set of the JavaScript String, Array and Number methods is available from a template (length, toUpperCase, replace, slice, split, indexOf, join, push, sort, toFixed and similar). The mutators change your Perl data in place, as they do in JavaScript. Missing: a template-level toString(), Array map/filter/reduce, toSorted, splice.

Calling Perl code (ADR 0009, 0016)

Keyword arguments arrive as a trailing hash reference carrying a marker. A Perl coderef called from a template gets no this; an object's method called as obj.method() gets the object. {{ obj.method }} without parentheses calls the method and renders its result, where JavaScript renders the function's source.

Errors (ADR 0010)

JavaScript's built-in errors are one class with a name and a message; the messages are those of the original.

Regular expressions (ADR 0005, 0013)

A regex literal becomes a Text::Nunjucks::Runtime::Regex object. A pattern Perl cannot express is refused when the template is compiled, never translated wrongly. \s, \d and \w follow ECMAScript's sets, with open problems: \d/\w/\s under the u flag, ^/$/. and JavaScript line terminators.

Names that exist on JavaScript's Object.prototype (ADR 0014)

A template variable resolves only to something you set, as a global or an own key of the context. toString, constructor, hasOwnProperty and the like are not found as variables. The same question for filter and test names, member reads and the groupby result is open.

Sorting (ADR 0017)

sort, dictsort and Array.sort are a port of V8's TimSort, so the order of equal and inconsistent comparisons matches node's.

Numbers are doubles on every perl (ADR 0019)

A number is an IEEE double even on a perl built with long double or quadmath NVs or with 4-byte IVs, so {{ 0.1 + 0.2 }} prints 0.30000000000000004 everywhere. Nothing changes on a double, 64-bit perl.

Scope and platform (ADR 0018, ADR 0022)

FileSystemLoader and PrecompiledLoader are ported (Text::Nunjucks::Loader::FileSystem, Text::Nunjucks::Loader::Precompiled). NodeResolveLoader, WebLoader, chokidar watch, the browser branches of Environment, express-app.js and precompile-global.js are out of scope. Node's path and fs are ported as their POSIX behaviour: / is the only separator, and paths follow the POSIX model of node's path. Windows paths (node's path.win32) come later; the tests that rest on the POSIX model (path resolution, directory and permission errors, file locks) are skipped on Windows, and all others run there.

Template code that outlives its render (ADR 0021)

A render holds its Context only for as long as something of it is still going to run, so a render leaves nothing behind. Three things follow. A macro, caller block or extension body that your own Perl code keeps and calls after the render that made it has ended dies at its first read of the template's variables, with template code ran after its render had ended: its Context is gone; one that reads only its own arguments works. An async filter or extension that calls its callback a second time dies in your event loop. If the result was already delivered, or the including render is still pending and the included template made no macro or call block, and what follows reads a variable, it dies with that error where Nunjucks calls the render callback again. If the first answer was an error and the importing render had ended before the second came, it dies where Nunjucks runs the rest of the importing template. And get_exported of Text::Nunjucks::Template returns every top-level function wrapped, so a coderef of yours that the template re-exports is not the same reference any more.

The random filter

random uses Perl's rand, upstream V8's Math.random: different generators, so the output is not comparable either way.

Upstream bugs kept (ADR 0004)

An upstream bug is ported, not fixed: the FileSystemLoader containment check is a string-prefix test and serves ../views2/x.njk for search path views; the lexer's back() reads a field that does not exist, in a branch that cannot be reached; render-time errors report a 0-based line and column while parse errors are 1-based.

Open differences

Known, not decided or not fixed yet. Each is a card; none is hidden.

Decisions waiting for the maintainer

Set and Map as context values, new String(...) wrappers and arrays with own properties cannot be built from Perl, and a toString member is not honoured; the Unicode version of case mapping follows the running perl, Unicode 15 on 5.40, not node's; V8's heap and string-length limits are not emulated, so an exhausting input (center(1/0)) runs until the OS stops it; the call stack is not limited either (ADR 0003): sequential includes and imports, asyncEach items, a template that includes itself and a macro that calls itself nest one Perl call per step, as upstream nests one JavaScript call, so where upstream stops with a RangeError (a few thousand asyncEach items or macro self-calls, a few hundred sequential includes) the port renders, bounded only by memory, and an endless recursion runs until memory is exhausted (whether to emulate the JavaScript engine's limits is undecided); engine methods that read this, such as cycler's next and reset, behave differently when called without memberLookup; a loader object that is not a Text::Nunjucks::Loader subclass and has only get_source is not accepted; a render that defers with no callback returns undef silently, as upstream returns null (the ADRs 0003 and 0009 say it dies); the print format of print_nodes is not byte-identical; the extension object shape; the top-level API.

Differences in what a template can see or do

A malformed from X import 3 succeeds where upstream throws a raw TypeError; an integer literal of 300 or more digits does not compile; the in operator converts its key the Perl way (true, null, arrays) and on a SafeString checks own keys only; split and replace with a regex argument stringify it; regex exec with g loses the context for lookahead, ^ and \b; code points are matched where JavaScript has UTF-16 units, in the lexer's column and in regexes; iterating a string or a SafeString with for and asyncEach over a string fail or iterate differently; a single-name for reads arr.length once; calling a non-callable member says undefined or falsey where JavaScript says not a function; {% set x.b = 1 %} dies with a Perl error; is not (test) with a parenthesised name crashes; .val on a SafeString reads empty; SafeString->new(5) returns the value; a __proto__ key in a dict literal is an own key; a macro's length and name read undefined; o.f yields the same function each time, not a new closure; a keyword-argument object returned to a template is opaque; an engine-built loop object and import namespace iterate sorted, not in insertion order; groupby with a key such as toString groups instead of throwing; autoescape uses Perl truthiness, so '0' turns it off; Math.pow and ** differ for exact-tie powers above 2**53; the template-name error message joins a non-string name the Perl way; Template->new with a Hash::Ordered source dies; JSON integers beyond 64 bits arrive as strings in the corpus harness.

LIMITATIONS

Memory

Keep one long-lived Text::Nunjucks::Environment. A cached template holds its Environment, so an Environment with a caching loader is never freed; a render keeps its context alive when it uses asyncEach or asyncAll with four or more loop names. Macros, caller blocks, imports and includes do not leak a render (ADR 0021), but they cost memory until the render ends: every executed import or from ... import keeps the library's context, so an import in a loop of 20,000 holds about 6 kB per round until the render is over, and so does an included template that made a macro or call block, about 8 kB for a macro with a dozen context variables (a plain partial is not kept). Contexts are still left behind when an included template that made a macro or call block fails inside an asyncEach, asyncAll or a for with an async filter after a deferral, when it hands a macro with an async construct to the including template and then never completes, and when an import fails inside one of those loops.

Speed

Compiling costs about 130 microseconds per source character, so reuse compiled templates and the Environment's cache. Rendering a 1000-row table is about 35 times slower than node; replace, title and the number-to-string step are slow on large input.

Unicode

Case mapping follows the Unicode tables of the running perl.

SECURITY

Text::Nunjucks::Loader::FileSystem keeps upstream's containment check, a string-prefix test: with search path views the name ../views2/x.njk is served, as is the sibling file ../views.env. The search path . serves the current directory and its siblings, and symlinks are followed. Never pass template names you do not control to render or get_template, and never render a template you do not trust: a template is code.

SEE ALSO

Text::Nunjucks::Environment, https://mozilla.github.io/nunjucks/

SUPPORT

Issues

Please report bugs and feature requests at https://github.com/Getty/p5-text-nunjucks/issues.

CONTRIBUTING

Contributions are welcome! Please fork the repository and submit a pull request.

AUTHOR

Torsten Raudssus <getty@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by Torsten Raudssus <torsten@raudssus.de> https://raudssus.de/.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.