pub struct Environment {
pub autoescape: bool,
pub dev: bool,
pub loader: Option<Arc<dyn TemplateLoader + Send + Sync>>,
pub globals: HashMap<String, Value>,
pub throw_on_undefined: bool,
pub random_seed: Option<u64>,
pub trim_blocks: bool,
pub lstrip_blocks: bool,
pub tags: Option<Tags>,
/* private fields */
}Expand description
Configuration and entry point for rendering templates.
§Fields
autoescape: Whentrue(the default), HTML-escapes string output from variable tags viacrate::filters::escape_html.dev: Reserved for developer-mode behavior (e.g. richer errors); currently unused in the renderer.throw_on_undefined: Whentrue, unbound variables are errors instead of the internal undefined sentinel.loader: OptionalTemplateLoaderforEnvironment::render_template,{% include %},{% import %},{% from %}, and{% extends %}.
§Default
Environment::default sets autoescape = true, dev = false, and loader = None.
§Examples
use runjucks_core::Environment;
use serde_json::json;
let mut env = Environment::default();
env.autoescape = false;
let out = env.render_string("<{{ x }}>".into(), json!({ "x": "b" })).unwrap();
assert_eq!(out, "<b>");Fields§
§autoescape: boolWhen true, variable output is passed through crate::filters::escape_html.
dev: boolDeveloper mode flag (reserved).
loader: Option<Arc<dyn TemplateLoader + Send + Sync>>Resolves template names for Environment::render_template, include, and extends.
globals: HashMap<String, Value>Nunjucks-style globals: used when a name is not bound in the template context (context wins if the key exists, including null).
throw_on_undefined: boolWhen true, an unbound variable name (not in context or globals) is a render error instead of crate::value::undefined_value.
random_seed: Option<u64>When set, crate::filters::apply_builtin random uses this seed for reproducible output (conformance / tests).
trim_blocks: boolWhen true, the first newline after a block tag ({% … %}) is automatically removed (Nunjucks trimBlocks).
lstrip_blocks: boolWhen true, leading whitespace/tabs on a line before a block tag or comment are stripped (Nunjucks lstripBlocks).
Custom delimiter strings (Nunjucks tags key in configure). None uses default delimiters.
Implementations§
Source§impl Environment
impl Environment
Sourcepub fn parse_or_cached_inline(&self, src: &str) -> Result<Arc<Node>>
pub fn parse_or_cached_inline(&self, src: &str) -> Result<Arc<Node>>
Parses template source using the inline parse cache (hash of source + parse signature).
Sourcepub fn clear_named_parse_cache(&self)
pub fn clear_named_parse_cache(&self)
Clears the named-template parse cache (e.g. after replacing the template loader).
Sourcepub fn invalidate_cache(&self)
pub fn invalidate_cache(&self)
Clears all parse caches: named templates ([load_and_parse_named]) and inline
[parse_or_cached_inline] entries (Nunjucks Environment#invalidateCache analog).
Sourcepub fn render_parsed(&self, ast: &Node, context: Value) -> Result<String>
pub fn render_parsed(&self, ast: &Node, context: Value) -> Result<String>
Renders a parsed AST without lexing/parsing (caller must use the same environment configuration as when the AST was produced).
Sourcepub fn add_global(&mut self, name: impl Into<String>, value: Value) -> &mut Self
pub fn add_global(&mut self, name: impl Into<String>, value: Value) -> &mut Self
Registers or replaces a global value (Nunjucks addGlobal). Names still lose to template context keys with the same name.
Replacing a global with a JSON value clears any registered Environment::add_global_callable for that name.
Sourcepub fn add_global_callable(
&mut self,
name: impl Into<String>,
f: CustomGlobalFn,
) -> &mut Self
pub fn add_global_callable( &mut self, name: impl Into<String>, f: CustomGlobalFn, ) -> &mut Self
Registers a global function implemented in Rust (tests / embedders). Node callers use NAPI addGlobal with a JS function.
The template sees a crate::globals::RJ_CALLABLE marker for is callable / variable resolution; invocation uses f.
Sourcepub fn add_filter(
&mut self,
name: impl Into<String>,
filter: CustomFilter,
) -> &mut Self
pub fn add_filter( &mut self, name: impl Into<String>, filter: CustomFilter, ) -> &mut Self
Registers or replaces a custom filter (Nunjucks addFilter). Overrides a built-in with the same name.
Sourcepub fn add_test(
&mut self,
name: impl Into<String>,
test: CustomTest,
) -> &mut Self
pub fn add_test( &mut self, name: impl Into<String>, test: CustomTest, ) -> &mut Self
Registers or replaces a custom is test (Nunjucks addTest). Used by x is name and by select / reject.
Sourcepub fn register_extension(
&mut self,
extension_name: impl Into<String>,
tag_specs: Vec<(String, Option<String>)>,
handler: CustomExtensionHandler,
) -> Result<()>
pub fn register_extension( &mut self, extension_name: impl Into<String>, tag_specs: Vec<(String, Option<String>)>, handler: CustomExtensionHandler, ) -> Result<()>
Registers a custom tag extension (Nunjucks addExtension): tag_specs lists (opening_tag, optional_end_tag).
Sourcepub fn has_extension(&self, name: &str) -> bool
pub fn has_extension(&self, name: &str) -> bool
Returns whether a custom extension with this name is registered (Nunjucks hasExtension).
Sourcepub fn get_extension_descriptor(
&self,
name: &str,
) -> Option<ExtensionDescriptor>
pub fn get_extension_descriptor( &self, name: &str, ) -> Option<ExtensionDescriptor>
Returns metadata for a registered extension name without exposing the internal handler.
Sourcepub fn remove_extension(&mut self, name: &str) -> bool
pub fn remove_extension(&mut self, name: &str) -> bool
Unregisters a custom extension by name (Nunjucks removeExtension). Returns true if it existed.
Sourcepub fn validate_lex_parse(&self, src: &str) -> Result<()>
pub fn validate_lex_parse(&self, src: &str) -> Result<()>
Lexes and parses src with this environment’s extension tags (for eager-compile validation).
Sourcepub fn resolve_variable_ref<'a>(
&'a self,
stack: &'a CtxStack,
name: &str,
) -> Result<Cow<'a, Value>>
pub fn resolve_variable_ref<'a>( &'a self, stack: &'a CtxStack, name: &str, ) -> Result<Cow<'a, Value>>
Resolves a name: template context first (any frame), then Environment::globals.
Unbound names yield crate::value::undefined_value unless Environment::throw_on_undefined is set.
Borrows context/globals when possible to avoid cloning on hot paths (see Self::resolve_variable).
Sourcepub fn resolve_variable(&self, stack: &CtxStack, name: &str) -> Result<Value>
pub fn resolve_variable(&self, stack: &CtxStack, name: &str) -> Result<Value>
Unbound names yield crate::value::undefined_value unless Environment::throw_on_undefined is set.
Sourcepub fn lexer_options(&self) -> LexerOptions
pub fn lexer_options(&self) -> LexerOptions
Returns the LexerOptions derived from this environment’s configuration.
Sourcepub fn render_string(&self, template: String, context: Value) -> Result<String>
pub fn render_string(&self, template: String, context: Value) -> Result<String>
Lexes template, parses it to an AST, and renders it with context.
§Errors
Returns crate::errors::RunjucksError when:
- The
crate::lexerfinds malformed delimiters (e.g. unclosed{{). - The
crate::parserhits unsupported tag syntax. - Rendering fails (currently rare; lookup errors use Nunjucks-style defaults).
§Examples
use runjucks_core::Environment;
use serde_json::json;
let env = Environment::default();
let html = env
.render_string("{{ msg }}".into(), json!({ "msg": "<ok>" }))
.unwrap();
assert_eq!(html, "<ok>");Sourcepub fn render_template(&self, name: &str, context: Value) -> Result<String>
pub fn render_template(&self, name: &str, context: Value) -> Result<String>
Renders a named template using the configured TemplateLoader.
Supports {% extends %}, {% include %}, {% import %}, {% from %}, and {% macro %} across files.
Trait Implementations§
Source§impl Clone for Environment
impl Clone for Environment
Source§fn clone(&self) -> Environment
fn clone(&self) -> Environment
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more