Environment

Struct Environment 

Source
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: When true (the default), HTML-escapes string output from variable tags via crate::filters::escape_html.
  • dev: Reserved for developer-mode behavior (e.g. richer errors); currently unused in the renderer.
  • throw_on_undefined: When true, unbound variables are errors instead of the internal undefined sentinel.
  • loader: Optional TemplateLoader for Environment::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: bool

When true, variable output is passed through crate::filters::escape_html.

§dev: bool

Developer 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: bool

When 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: bool

When true, the first newline after a block tag ({% … %}) is automatically removed (Nunjucks trimBlocks).

§lstrip_blocks: bool

When true, leading whitespace/tabs on a line before a block tag or comment are stripped (Nunjucks lstripBlocks).

§tags: Option<Tags>

Custom delimiter strings (Nunjucks tags key in configure). None uses default delimiters.

Implementations§

Source§

impl Environment

Source

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).

Source

pub fn clear_named_parse_cache(&self)

Clears the named-template parse cache (e.g. after replacing the template loader).

Source

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).

Source

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).

Source

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.

Source

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.

Source

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.

Source

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.

Source

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).

Source

pub fn has_extension(&self, name: &str) -> bool

Returns whether a custom extension with this name is registered (Nunjucks hasExtension).

Source

pub fn get_extension_descriptor( &self, name: &str, ) -> Option<ExtensionDescriptor>

Returns metadata for a registered extension name without exposing the internal handler.

Source

pub fn remove_extension(&mut self, name: &str) -> bool

Unregisters a custom extension by name (Nunjucks removeExtension). Returns true if it existed.

Source

pub fn validate_lex_parse(&self, src: &str) -> Result<()>

Lexes and parses src with this environment’s extension tags (for eager-compile validation).

Source

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).

Source

pub fn resolve_variable(&self, stack: &CtxStack, name: &str) -> Result<Value>

Source

pub fn lexer_options(&self) -> LexerOptions

Returns the LexerOptions derived from this environment’s configuration.

Source

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::lexer finds malformed delimiters (e.g. unclosed {{).
  • The crate::parser hits 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, "&lt;ok&gt;");
Source

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

Source§

fn clone(&self) -> Environment

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Environment

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Environment

Source§

fn default() -> Self

Returns an environment with autoescape = true and dev = false.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V