NAME
Text::Nunjucks::Environment - 1:1 port of Nunjucks src/environment.js -- the template Environment
VERSION
version 0.001
DESCRIPTION
The upstream file src/environment.js defines three classes. The port gives each its own file (ADR 0020): Text::Nunjucks::Environment, below, the object an application holds; Text::Nunjucks::Template, a template that renders; and Text::Nunjucks::Context, the per-render bookkeeping of variables and blocks, which the engine creates itself and callers do not use. Loading this module loads the other two. Callbacks follow ADR 0003 and the render API ADR 0009.
Every one of these classes takes its constructor arguments by position, as upstream's constructors do, not as a hash.
Text::Nunjucks::Environment
my $env = Text::Nunjucks::Environment->new( $loaders, \%opts );
$env->add_filter( reverse_words => sub { join ' ', reverse split ' ', $_[0] } );
my $out = $env->render( 'page.njk', { title => 'Hi' } );
An Environment owns the loaders, the options, the filters, tests, globals and extensions, and a cache of compiled templates per loader. Keep one around and render through it: a template is compiled once and cached.
new
Text::Nunjucks::Environment->new;
Text::Nunjucks::Environment->new( $loader );
Text::Nunjucks::Environment->new( [ $loader_a, $loader_b ], \%opts );
Positional: the loaders, then the options. $loaders is one loader object or an array reference of them, tried in order. When it is omitted (or false) the Environment uses a single Text::Nunjucks::Loader::FileSystem over the directory views of the current working directory. An empty array reference means no loaders: only render_string can then render, and render fails with template not found.
The options are a hash reference with the keys of Nunjucks:
- autoescape
-
Escape every output with
{{ }}unless it is marked safe. True by default: anundefor null value leaves the default in place, any other value is taken as given. - throwOnUndefined
-
Make outputting an undefined or null value an error (
attempted to output null or undefined value). Off by default. - trimBlocks
-
Remove the first newline after a block tag. Off by default.
- lstripBlocks
-
Remove leading whitespace from the start of a line up to a block tag. Off by default.
- dev
-
Throw the error objects as they are (Text::Nunjucks::Lib::TemplateError, with line, column and cause) instead of the plain Text::Nunjucks::Lib::Error carrying the same name and message. Off by default. Errors that are not template errors, such as
template not found, are Text::Nunjucks::Lib::Error either way. -
A hash reference overriding the template delimiters: any of
blockStart,blockEnd,variableStart,variableEnd,commentStart,commentEnd. The defaults are{%,%},{{,}},{#and#}.
The option keys keep their JavaScript spelling because they are the names of the template engine's options. The hash reference you pass is the Environment's opts itself, changed in place: the defaults are filled in, and the four boolean options become booleans.
loaders
Array reference of the loaders, in lookup order.
opts
The options hash reference, with defaults filled in. It is the hash you passed to new, not a copy.
globals
Hash reference of the global names to values. Use "add_global" and "get_global" instead of writing to it.
filters
Hash reference of the filter names to code references. Use "add_filter" and "get_filter".
tests
Hash reference of the is test names to code references. Use "add_test" and "get_test".
async_filters
Array reference of the names of the filters registered as asynchronous.
extensions
Hash reference of the extension names to extensions, and extensions_list the same extensions as an array reference in registration order. Use "add_extension".
add_filter
$env->add_filter( shout => sub { my ($text) = @_; return uc($text) . '!' } );
$env->add_filter( $name, sub { my ( $value, @args ) = @_; ... } );
$env->add_filter( $name, sub { my $cb = pop; my ( $value, @args ) = @_; $cb->( $err, $result ) }, 1 );
Registers a filter and returns the Environment. A synchronous filter is called with the value being filtered followed by the filter's arguments and returns the result. With a true third argument the filter is asynchronous: it receives a trailing callback instead of returning, and calls $cb->( $err, $result ) (ADR 0009); take the callback off the end of @_ first, as in the example. Keyword arguments in the template arrive as a trailing Text::Nunjucks::Runtime::KwArgs object; for an asynchronous filter it comes before the callback. A name registered twice is replaced, so a built-in filter can be overridden.
get_filter
my $code = $env->get_filter($name);
Returns the filter's code reference. Dies with a Text::Nunjucks::Lib::Error filter not found: NAME when there is none.
add_test
$env->add_test( $name, sub { my ( $value, @args ) = @_; ... } );
Registers an is test ({{ x is NAME }}) and returns the Environment. The code reference gets the tested value and the test's arguments and returns the truth value.
get_test
my $code = $env->get_test($name);
Returns the test's code reference. Dies with test not found: NAME when there is none.
add_global
$env->add_global( $name, $value );
Sets a global, visible to every template rendered through this Environment unless the context has a variable of the same name. A code reference is a function the template can call. Returns the Environment.
get_global
my $value = $env->get_global($name);
Returns the global. Dies with global not found: NAME when it is not set (or undefined). The built-in globals are range, cycler and joiner.
add_extension
$env->add_extension( $name, $extension );
Registers an extension and returns the Environment. $extension must be a hash-based object; the Environment stores $name in its __name key. How an extension object is shaped (the tags it claims and how it parses and renders them) is not settled and not documented here.
get_extension
my $extension = $env->get_extension($name);
Returns the registered extension, or undef.
has_extension
True when an extension of that name is registered.
remove_extension
$env->remove_extension($name);
Unregisters the extension. Does nothing when there is none.
get_template
my $tmpl = $env->get_template($name);
my $tmpl = $env->get_template( $name, $eager_compile, $parent_name, $ignore_missing );
$env->get_template( $name, $eager_compile, $parent_name, $ignore_missing, sub {
my ( $err, $tmpl ) = @_;
} );
Returns the Text::Nunjucks::Template called $name. The cache of each loader is consulted first, then each loader's get_source in turn until one returns a source; a source whose noCache is false is cached under the resolved name ($name resolved against $parent_name, see below). $name may also be a template object, which is returned as it is.
$eager_compile compiles the template now instead of on its first render. $parent_name is the name of the template doing the asking: a $name that starts with ./ or ../ is resolved against it (see "resolve_template"). With a true $ignore_missing a template no loader has is an empty template instead of an error.
Without a callback the template is returned, or the method dies with a Text::Nunjucks::Lib::Error (template not found: NAME, or template names must be a string: ...). The callback is the fifth argument, or takes the place of $eager_compile or $parent_name (and the arguments after it). It cannot take the place of $ignore_missing: a code reference there is only a true value, and the callback is never called. With a callback, errors go to $cb->($err) and the template to $cb->( undef, $tmpl ). A loader that is asynchronous (see Text::Nunjucks::Loader) can only be used with a callback: without one, the method returns before the template has arrived.
resolve_template
my $name = $env->resolve_template( $loader, $parent_name, $filename );
Returns the name to look up: $filename resolved against $parent_name by the loader's resolve when the filename is relative (./x, ../x), the parent name is given and the loader has is_relative and resolve; otherwise $filename unchanged.
render
my $html = $env->render( 'page.njk', \%context );
$env->render( 'page.njk', \%context, sub { my ( $err, $html ) = @_; ... } );
Loads the template with get_template and renders it with the context hash reference (the context may be left out). Without a callback it returns the text and dies on error. With a callback it calls $cb->( $err, $result ), exactly one of the two being set; errors in loading and rendering the template go there instead of dying. A name that is not a string (render( undef, {}, $cb )) still dies before the callback is reached, as in Nunjucks. Rendering is synchronous unless something in the template or its loaders defers; a render without a callback that does defer returns undef without an error, as Nunjucks returns null. A failed render is a Text::Nunjucks::Lib::Error, or a Text::Nunjucks::Lib::TemplateError with dev; template not found is a Text::Nunjucks::Lib::Error in both cases.
render_string
my $html = $env->render_string( $source, \%context );
my $html = $env->render_string( $source, \%context, { path => 'inline.njk' } );
$env->render_string( $source, \%context, $opts, sub { my ( $err, $html ) = @_; ... } );
Renders a template given as a string, with this Environment's filters, tests, globals and loaders (so include and extends inside it work). The third argument is a hash reference whose only key is path, the name shown in error messages (unknown path otherwise); it may be left out, and the callback given in its place. Return value, errors and callback are as for "render".
invalidate_cache
$env->invalidate_cache;
Empties the compiled-template cache of every loader.
on
$env->on( update => sub { my ( $name, $fullname, $loader ) = @_; ... } );
$env->on( load => sub { my ( $name, $source, $loader ) = @_; ... } );
From Text::Nunjucks::EmitterObj. The Environment re-emits its loaders' events: update when a loader reports that a template changed (the loader's cache entry for it is dropped first), and load when a loader emits it (Text::Nunjucks::Loader::FileSystem does when it reads a template; Text::Nunjucks::Loader::Precompiled never does). Both carry the loader as the last argument. emit calls the listeners in registration order.
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.