gd_jinja¶
gd-jinja: a standalone Jinja 3.x template engine.
It supports Jinja’s tags, filters, tests and globals, template inheritance, macros, autoescaping, and Elm-style error reports, without a Python environment.
use gd_jinja::{Environment, Options, Autoescape, Value};
let env = Environment::new(Options { autoescape: Autoescape::Always, ..Options::default() });
let ctx = Value::dict();
ctx.set("name", Value::from("<World>"));
let out = env.render_str("Hello {{ name }}!", &ctx).unwrap();
assert_eq!(out, "Hello <World>!");
Every failure is an Error whose Display is the Elm-style report; nothing panics on bad templates or data. See the crate README for the cheat sheet.
Structs
- pub struct gd_jinja::Call<'a, 'env>¶
-
What a native procedure receives: the positional and keyword arguments (for a filter or test,
args[0]is the value being filtered or tested), the receiver of a bound method, and the name it was called by. It borrows the render running it.Fields
- pub name: Rc<str>¶
-
The name the procedure was registered or looked up by.
Implementations
- impl<'a, 'env> Call<'a, 'env>
-
- pub fn arg(&self, index: usize, name: &str) -> Value¶
-
Positional argument
index, else the keyword argumentname, else Undefined.
- pub fn arg_or(&self, index: usize, name: &str, default: Value) -> Value¶
-
Positional argument
index, else the keyword argumentname, elsedefault.
- pub fn has_arg(&self, index: usize, name: &str) -> bool¶
-
Whether the argument was passed at all.
- pub fn arg_flag(&self, index: usize, name: &str, default: bool) -> bool¶
-
Whether argument
index/nameis true, ordefaultwhen it was not passed.
- pub fn arg_int(&self, index: usize, name: &str, default: i64) -> std::result::Result<i64, Error>¶
-
An integer argument; bools and floats are accepted, and None gives
default.
- pub fn arg_count(&self, index: usize, name: &str, default: i64) -> std::result::Result<usize, Error>¶
-
Like
Call::arg_int, with negative values read as 0.
- pub fn check_args(&self, who: &str, names: &[&str], required: usize) -> std::result::Result<(), Error>¶
-
Enforces a Python signature: at most
names.len()positional arguments, only the named keywords, each once, and the firstrequiredpresent.whonames the callable in errors.
- pub fn error(&self, message: &str) -> Error¶
-
An error at the place the call happens, for the procedure to return.
- pub fn autoescaping(&self) -> bool¶
-
Whether autoescape is on where the call happens.
Trait Implementations
- impl std::fmt::Debug for Call<'_, '_>
-
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
- pub struct gd_jinja::Keyword¶
-
One keyword argument of a call.
Fields
- pub name: Rc<str>¶
-
The parameter name.
- pub struct gd_jinja::Environment¶
-
Options, filters, tests, globals and the template cache. An environment is not thread-safe; use one per thread.
Fields
Implementations
- impl Environment
-
- pub fn new(options: Options) -> Environment¶
-
Makes an environment with the built-in filters, tests and globals.
- pub fn add_filter(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'static)¶
-
Registers a filter:
call.args[0]is the filtered value.
- pub fn add_test(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'static)¶
-
Registers a test:
call.args[0]is the tested value; its truthiness is the answer.
- pub fn add_function(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'static)¶
-
Registers a native procedure as a global function.
- pub fn clear_cache(&self)¶
-
Forgets parsed templates, so the next load reads them again.
- pub fn take_template_loads(&self) -> Vec<String>¶
-
Takes the names requested since the last call, sorted and deduplicated. Includes cached templates and missing names, including
ignore missinglookups.
- pub fn load_template(&self, name: &str) -> Result<Template<'_>, Error>¶
-
Loads a template through the loader, cached until clear_cache.
- pub fn parse_template(&self, name: &str, source: &str) -> Result<Template<'_>, Error>¶
-
Parses source as a template called name; it is not cached, so extends and include do not find it (see add_template).
- pub fn add_template(&self, name: &str, source: &str) -> Result<(), Error>¶
-
Parses source and caches it under name, so that extends, include and import find it without a loader.
- pub fn render_str(&self, source: &str, ctx: &Value) -> Result<String, Error>¶
-
Parses and renders source once, caching nothing.
ctxis a dict value, or Undefined for none.
Trait Implementations
- impl fmt::Debug for Environment
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- impl Default for Environment
-
- fn default() -> Environment
- pub struct gd_jinja::Options¶
-
Plain options; fill the ones you need with struct-update syntax:
Options { autoescape: Autoescape::Always, ..Options::default() }.Fields
- pub autoescape: Autoescape¶
-
Which templates escape their output.
- pub trim_blocks: bool¶
-
Drop the first newline after a block tag.
- pub lstrip_blocks: bool¶
-
Strip spaces and tabs before a block tag at the start of a line.
- pub keep_trailing_newline: bool¶
-
Keep the source’s final newline.
- pub undefined: UndefinedMode¶
-
How undefined values behave.
- pub max_recursion: usize¶
-
How deep macros, includes, blocks and recursive loops may nest.
- pub max_iterations: usize¶
-
Loop iterations (and
range()sizes) per render.
- pub max_output: usize¶
-
Bytes of output per render, and per value a render builds (a repetition, padding, a join), checked before it is allocated; 0 means unlimited.
- pub max_nesting: usize¶
-
How deep template syntax nests: brackets, tags, and operator, filter, attribute and elif chains.
- pub stack_bytes: usize¶
-
The machine stack parsing and rendering may use. Run on a thread whose stack is at least this plus what your caller and your filters need.
- pub random_seed: u64¶
-
Seeds
randomandlipsum; 0 picks a fixed seed. Renders are deterministic.
Trait Implementations
- pub struct gd_jinja::Template<'env>¶
-
A parsed template, ready to render. It borrows its environment.
Implementations
- impl Template<'_>
-
- pub fn name(&self) -> &str¶
-
The template’s name.
- pub fn render(&self, ctx: &Value) -> Result<String, Error>¶
-
Renders the template with ctx (a dict value, or Undefined for none).
- pub fn render_with(&self, ctx: &Value, locals: &Locals<'_>) -> Result<String, Error>¶
-
Renders the template with ctx and the render’s own functions and filters (
locals), which may borrow the caller’s data. They are visible in every template, block, macro and call block of this render and shadow the environment’s globals and filters of the same name.
- pub struct gd_jinja::Error¶
-
A failure to parse or render.
excerptis the template line the error points at;hint, when not empty, suggests a fix.Displayrenders an Elm-style report:-- UNDEFINED VALUE -------------------------------------------------- page.html:3 'usr' is undefined 3| <h1>{{ usr.name }}</h1> Hint: Did you mean 'user'?Fields
- pub line: usize¶
-
The 1-based line, or 0 when unknown.
Implementations
- impl Error
Trait Implementations
- impl fmt::Display for Error
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- impl std::error::Error for Error
- pub struct gd_jinja::Locals<'a>¶
-
The functions and filters one render adds to its environment’s.
use gd_jinja::{Environment, Locals, Value}; let titles = vec!["Intro".to_string(), "Usage".to_string()]; let mut locals = Locals::new(); locals.add_function("title", |c| { let i = c.arg_count(0, "index", 0)?; Ok(Value::from(titles.get(i).map_or("", String::as_str))) }); let out = Environment::default().render_str_with("{{ title(1) }}", &Value::default(), &locals); assert_eq!(out.unwrap(), "Usage");
Implementations
- impl<'a> Locals<'a>
Trait Implementations
- impl fmt::Debug for Locals<'_>
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- pub struct gd_jinja::State<'env>¶
-
One render in progress. Native procedures reach it through
crate::Call.Trait Implementations
- impl std::fmt::Debug for State<'_>
-
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
- pub struct gd_jinja::Callable¶
-
A function value.
Implementations
- impl Callable
-
- pub fn name(&self) -> &str¶
-
The name the function was registered or defined with.
- pub fn is_macro(&self) -> bool¶
-
Whether this is a macro (or a call block’s
caller).
Trait Implementations
- impl fmt::Debug for Callable
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- pub struct gd_jinja::Cycler¶
-
The object made by the
cycler()global.Trait Implementations
- impl fmt::Debug for Cycler
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- pub struct gd_jinja::Dict¶
-
An insertion-ordered dictionary. String keys are indexed; other keys are compared with Python equality (
1 == 1.0 == True).Implementations
- impl Dict
-
- pub fn begin_key_trace(&self)¶
-
Starts recording string-key reads, including missing keys. Replaces any prior trace.
- pub fn end_key_trace(&self) -> Vec<String>¶
-
Stops recording and returns distinct keys in sorted order; empty if tracing was off.
- pub fn name(&self) -> &str¶
-
The template name of a module; empty otherwise.
- pub fn len(&self) -> usize¶
-
The number of entries.
- pub fn is_empty(&self) -> bool¶
-
Whether the dict has no entries.
- pub fn remove(&self, key: &Value) -> Option<Value>¶
-
Removes the entry under
keyand returns its value.
- pub fn clear(&self)¶
-
Removes every entry.
Trait Implementations
- impl fmt::Debug for Dict
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- impl Drop for Dict
-
- fn drop(&mut self)
- pub struct gd_jinja::List¶
-
A list, or a tuple when
is_tuple. A named tuple (the groupsgroupbymakes) can also be read through its field names.Implementations
- impl List
-
- pub fn new(items: Vec<Value>, tuple: bool) -> Rc<List>¶
-
Makes a shared list (or tuple) holding
items.
- pub fn items(&self) -> Ref<'_, Vec<Value>>¶
-
Borrows the items. Panics if a template is changing the list at that moment, which cannot happen outside a native procedure that changes it itself.
- pub fn len(&self) -> usize¶
-
The number of items.
- pub fn is_empty(&self) -> bool¶
-
Whether the list has no items.
- pub fn is_tuple(&self) -> bool¶
-
Whether this is a tuple.
Trait Implementations
- impl fmt::Debug for List
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- impl Drop for List
-
- fn drop(&mut self)
- pub struct gd_jinja::Loop¶
-
The special
loopvariable of a for loop.Implementations
- impl Loop
-
- pub fn index0(&self) -> usize¶
-
The 0-based index of the current iteration.
- pub fn len(&self) -> usize¶
-
The number of items the loop runs over.
- pub fn is_empty(&self) -> bool¶
-
Whether the loop runs over no items.
Trait Implementations
- impl fmt::Debug for Loop
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- pub struct gd_jinja::Undefined¶
-
What a missing variable, attribute or item evaluates to. The fields only feed the error message produced when the value is used in a way Jinja forbids.
Fields
- pub name: Rc<str>¶
-
The missing variable or attribute.
- pub owner: Rc<str>¶
-
"dict object"when an attribute or item was missing, else empty.
- pub hint: Rc<str>¶
-
A complete message that replaces the generated one, or empty.
Enums
- pub enum gd_jinja::Autoescape¶
-
Which templates HTML-escape the
{{ }}output that is not Markup.Variants
- Never¶
-
No template does.
- Always¶
-
Every template does.
- pub enum gd_jinja::UndefinedMode¶
-
How undefined values behave, like Jinja’s Undefined classes.
Variants
- Default¶
-
Renders as “”, fails on attribute access, calls and arithmetic.
- Strict¶
-
Fails on every use except
is definedand|default.
- Chainable¶
-
Like Default, but attributes of undefined values are undefined too.
- Debug¶
-
Like Default, but renders as
{{ name }}.
- pub enum gd_jinja::ErrorKind¶
-
What kind of failure an
Errorreports.Variants
- Syntax¶
-
The template does not parse (Jinja’s TemplateSyntaxError).
- Undefined¶
-
An undefined value was used (UndefinedError).
- Type¶
-
An operation got the wrong kind of value (TypeError).
- NotFound¶
-
A template could not be loaded (TemplateNotFound).
- Limit¶
-
A recursion, nesting, iteration, output or stack limit was reached.
- Memory¶
-
A value too large to count or to allocate was asked for (MemoryError).
- Runtime¶
-
Any other failure while rendering.
Implementations
- pub enum gd_jinja::Loader¶
-
A source of templates by name.
Variants
- Filesystem(Vec<PathBuf>)¶
-
The first of these directories that holds the name; names use “/” and may not climb out of a directory with “..”.
Implementations
- impl Loader
-
- pub fn memory<N: Into<String>, S: Into<String>>(sources: impl IntoIterator<Item = (N, S)>) -> Loader¶
-
A loader serving the given (name, source) pairs.
- pub fn filesystem<P: Into<PathBuf>>(directories: impl IntoIterator<Item = P>) -> Loader¶
-
A loader reading from directories, searched in order.
Trait Implementations
- impl fmt::Debug for Loader
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- pub enum gd_jinja::DictKind¶
-
What a
Dictis.Variants
- Dict¶
-
A plain dict.
- Namespace¶
-
namespace(): the only object whose attributes templates may assign.
- Module¶
-
The result of
{% import %}: exported macros and variables.
- pub enum gd_jinja::Value¶
-
Every value a template can see. The default value is Undefined.
Lists, dicts and the other containers are shared (
Rc): cloning a value shares it, as Python shares objects.Variants
- Undefined(Option<Rc<Undefined>>)¶
-
A missing value, with the details its error message names when there are any.
- None¶
-
Python’s
None.
- Bool(bool)¶
-
TrueorFalse.
- Int(i64)¶
-
A 64-bit integer; overflow is an error, not a wrap.
- Float(f64)¶
-
A float.
- Str(Rc<str>)¶
-
A string.
- Markup(Rc<str>)¶
-
A string that is already safe HTML: autoescaping leaves it alone.
Implementations
- impl Value
-
- pub fn markup(s: &str) -> Value¶
-
Makes a string value that is safe HTML, which autoescaping leaves alone.
- pub fn undefined(name: &str) -> Value¶
-
Makes an undefined value;
nameis what error messages call it.
- pub fn dict() -> Value¶
-
Makes an empty dict; fill it with
Value::set.
- pub fn function(name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'static) -> Value¶
-
Wraps a native procedure as a callable value for globals or context data.
- pub fn set(&self, key: &str, value: Value)¶
-
Stores
valueunder the stringkeyof a dict value; nothing happens when this is not a dict.
- pub fn get(&self, key: &str) -> Value¶
-
Reads a string key from a dict value; missing keys give Undefined.
- pub fn push(&self, item: Value)¶
-
Appends
itemto a list value; nothing happens when this is not a list.
- pub fn len(&self) -> usize¶
-
The number of items of a list or dict, or of characters of a string; 0 otherwise.
- pub fn is_empty(&self) -> bool¶
-
Whether
Value::lenis 0.
- pub fn is_undefined(&self) -> bool¶
-
Whether the value is undefined.
- pub fn is_none(&self) -> bool¶
-
Whether the value is None.
- pub fn is_markup(&self) -> bool¶
-
Whether the value is safe HTML.
- pub fn is_string(&self) -> bool¶
-
Whether the value is a string or Markup.
- pub fn is_truthy(&self) -> bool¶
-
Python truthiness (Undefined is false).
- pub fn type_name(&self) -> &'static str¶
-
The Python type name used in Jinja’s error messages (
"str","dict", …).
Trait Implementations
- impl fmt::Debug for Value
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
- impl fmt::Display for Value
-
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
-
Writes the value as Python’s
str()does (Undefined writes nothing).
Functions
- pub fn gd_jinja::to_str(v: &Value) -> Cow<'_, str>¶
-
Converts a value as Python’s
str()does (Undefined gives “”). A string or Markup value is borrowed; anything else is written into a new string.
- pub fn gd_jinja::escape(v: &Value) -> Value¶
-
Converts a value to Markup: Markup stays as it is, everything else is converted to a string and escaped (MarkupSafe’s
escape()).
- pub fn gd_jinja::escape_string(s: &str) -> Cow<'_, str>¶
-
Replaces the five HTML special characters as MarkupSafe does; text that has none is borrowed.
- pub fn gd_jinja::render_str(source: &str, ctx: &Value) -> Result<String, Error>¶
-
Renders source once with ctx (a dict value, or Undefined for none) in a default environment: the one-call path.
Errors
Returns the parse or render error, whose
Displayis an Elm-style report.
Type Aliases
- pub type gd_jinja::LoadFn = Rc<dyn Fn(&str) -> Option<String>>¶
-
A procedure returning the source of a template by name, or None.
- pub type gd_jinja::LocalFn<'a> = dyn Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'a¶
-
A native procedure of one render; it may borrow data that lives for
'a.
- pub type gd_jinja::Native = Rc<dyn Fn(&mut Call<'_, '_>) -> Result<Value, Error>>¶
-
The one signature of every filter, test, global function and method written in Rust. Report errors by returning
Err(call.error("...")).
Constants
- pub const gd_jinja::MAX_VALUE_DEPTH: usize = 200¶
-
How deep repr, equality, ordering and tojson follow nested lists and dicts.
- pub const gd_jinja::DEFAULT_MAX_NESTING: usize = 100¶
-
How deep a template’s syntax may nest by default.
- pub const gd_jinja::DEFAULT_MAX_RECURSION: usize = 200¶
-
How deep macros, includes, blocks and recursive loops may nest by default.
- pub const gd_jinja::DEFAULT_STACK_BYTES: usize¶
-
The stack parsing and rendering may use by default. It fits the 2 MiB stack of a thread Rust spawns, with room for the caller, and holds
DEFAULT_MAX_RECURSIONlevels of recursion andDEFAULT_MAX_NESTINGlevels of syntax with room to spare. Unoptimized builds have larger frames (about 6 KiB per level of macro recursion and 3.5 KiB per bracket, against 2 KiB and 1.5 KiB optimized) and get a larger budget.