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<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_stringandget_template. Loading it also loads Text::Nunjucks::Template (a compiled template, the objectget_templatereturns 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/emitrole 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"and1behave as in JavaScript. Data from a JSON module arrives right; build values with0+$xor"$x"when in doubt. A Perlundefis the template'sundefined;nullis the singletonText::Nunjucks::Runtime->None(a JSONnullin 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::IxHashis 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,ArrayandNumbermethods is available from a template (length,toUpperCase,replace,slice,split,indexOf,join,push,sort,toFixedand similar). The mutators change your Perl data in place, as they do in JavaScript. Missing: a template-leveltoString(), Arraymap/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 asobj.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
nameand amessage; the messages are those of the original. - Regular expressions (ADR 0005, 0013)
-
A regex literal becomes a
Text::Nunjucks::Runtime::Regexobject. A pattern Perl cannot express is refused when the template is compiled, never translated wrongly.\s,\dand\wfollow ECMAScript's sets, with open problems:\d/\w/\sunder theuflag,^/$/.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,hasOwnPropertyand the like are not found as variables. The same question for filter and test names, member reads and thegroupbyresult is open. - Sorting (ADR 0017)
-
sort,dictsortandArray.sortare 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 doubleorquadmathNVs or with 4-byte IVs, so{{ 0.1 + 0.2 }}prints0.30000000000000004everywhere. Nothing changes on a double, 64-bit perl. - Scope and platform (ADR 0018, ADR 0022)
-
FileSystemLoaderandPrecompiledLoaderare ported (Text::Nunjucks::Loader::FileSystem, Text::Nunjucks::Loader::Precompiled).NodeResolveLoader,WebLoader, chokidarwatch, the browser branches ofEnvironment,express-app.jsandprecompile-global.jsare out of scope. Node'spathandfsare ported as their POSIX behaviour:/is the only separator, and paths follow the POSIX model of node'spath. Windows paths (node'spath.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,
callerblock 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, withtemplate 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 orcallblock, 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. Andget_exportedof 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
-
randomuses Perl'srand, upstream V8'sMath.random: different generators, so the output is not comparable either way. - Upstream bugs kept (ADR 0004)
-
An upstream bug is ported, not fixed: the
FileSystemLoadercontainment check is a string-prefix test and serves../views2/x.njkfor search pathviews; the lexer'sback()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 atoStringmember 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,asyncEachitems, 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 aRangeError(a few thousandasyncEachitems 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 readthis, such ascycler'snextandreset, behave differently when called withoutmemberLookup; a loader object that is not aText::Nunjucks::Loadersubclass and has onlyget_sourceis not accepted; a render that defers with no callback returnsundefsilently, as upstream returnsnull(the ADRs 0003 and 0009 say it dies); the print format ofprint_nodesis 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 3succeeds where upstream throws a rawTypeError; an integer literal of 300 or more digits does not compile; theinoperator converts its key the Perl way (true,null, arrays) and on aSafeStringchecks own keys only;splitandreplacewith a regex argument stringify it; regexexecwithgloses 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 aSafeStringwithforandasyncEachover a string fail or iterate differently; a single-nameforreadsarr.lengthonce; calling a non-callable member saysundefined or falseywhere JavaScript saysnot a function;{% set x.b = 1 %}dies with a Perl error;is not (test)with a parenthesised name crashes;.valon aSafeStringreads empty;SafeString->new(5)returns the value; a__proto__key in a dict literal is an own key; a macro'slengthandnameread undefined;o.fyields 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;groupbywith a key such astoStringgroups instead of throwing;autoescapeuses Perl truthiness, so'0'turns it off;Math.powand**differ for exact-tie powers above 2**53; the template-name error message joins a non-string name the Perl way;Template->newwith aHash::Orderedsource 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
asyncEachorasyncAllwith four or more loop names. Macros,callerblocks, imports and includes do not leak a render (ADR 0021), but they cost memory until the render ends: every executedimportorfrom ... importkeeps 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 orcallblock, 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 orcallblock fails inside anasyncEach,asyncAllor aforwith 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 animportfails 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,titleand 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.