Guidedog Manual 1.0.0-beta.16
Language
On this page
Guidedog / Documentation 1.0.0-beta.16

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 &lt;World&gt;!");

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 args: Vec<Value>

Positional arguments.

pub kwargs: Vec<Keyword>

Keyword arguments, in the order given.

pub this: Value

The receiver of a bound method; Undefined otherwise.

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 argument name, else Undefined.

pub fn arg_or(&self, index: usize, name: &str, default: Value) -> Value

Positional argument index, else the keyword argument name, else default.

pub fn keyword(&self, name: &str) -> Option<Value>

The keyword argument name, if it was passed.

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 / name is true, or default when 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 first required present. who names 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.

pub fn call_filter(&mut self, name: &str, args: Vec<Value>, kwargs: Vec<Keyword>) -> std::result::Result<Value, Error>

Runs a registered filter by name.

pub fn call_test(&mut self, name: &str, args: Vec<Value>, kwargs: Vec<Keyword>) -> std::result::Result<bool, Error>

Runs a registered test by name.

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 value: Value

The value passed.

pub struct gd_jinja::Environment

Options, filters, tests, globals and the template cache. An environment is not thread-safe; use one per thread.

Fields

pub options: Options

The options it was made with.

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_global(&mut self, name: &str, value: Value)

Makes a value visible to every template.

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 missing lookups.

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. ctx is a dict value, or Undefined for none.

pub fn render_str_with(&self, source: &str, ctx: &Value, locals: &Locals<'_>) -> Result<String, Error>

Parses source and renders it once with ctx and the render’s own functions and filters (locals), which may borrow the caller’s data; caches nothing.

pub fn evaluate(&self, expression: &str, ctx: &Value) -> Result<Value, Error>

Evaluates one expression against ctx (Jinja’s compile_expression).

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 loader: Option<Loader>

Where load_template, extends, include and import read from.

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 random and lipsum; 0 picks a fixed seed. Renders are deterministic.

Trait Implementations

impl Default for Options
fn default() -> Options
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. excerpt is the template line the error points at; hint, when not empty, suggests a fix. Display renders an Elm-style report:

-- UNDEFINED VALUE -------------------------------------------------- page.html:3

'usr' is undefined

3| <h1>{{ usr.name }}</h1>

Hint: Did you mean 'user'?

Fields

pub kind: ErrorKind

What kind of failure this is.

pub template: String

The template’s name; empty when there is none.

pub line: usize

The 1-based line, or 0 when unknown.

pub message: String

The plain explanation.

pub excerpt: String

The text of the line the error points at.

pub hint: String

How to fix it; empty when there is no suggestion.

Implementations

impl Error
pub fn new(kind: ErrorKind, line: usize, message: impl Into<String>) -> Error

Makes an error of kind with message; the render that returns it fills in where.

pub fn with_hint(mut self, hint: impl Into<String>) -> Error

Returns the error with hint attached, unless it already has one.

Trait Implementations

impl fmt::Display for Error
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl std::error::Error for Error
impl From<Box<Error>> for Error
fn from(err: Box<Error>) -> 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>
pub fn new() -> Locals<'a>

No functions or filters.

pub fn add_function(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'a) -> &mut Locals<'a>

Adds a function called name, replacing one added before under that name.

pub fn add_filter(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result<Value, Error> + 'a) -> &mut Locals<'a>

Adds a filter called name (call.args[0] is the value filtered), replacing one added before under that name.

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 new(kind: DictKind) -> Rc<Dict>

Makes an empty shared dict of kind.

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 kind(&self) -> DictKind

What the dict is.

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 get(&self, key: &Value) -> Option<Value>

The value stored under key.

pub fn get_str(&self, key: &str) -> Option<Value>

The value stored under the string key.

pub fn set(&self, key: Value, value: Value)

Adds or replaces an entry.

pub fn remove(&self, key: &Value) -> Option<Value>

Removes the entry under key and returns its value.

pub fn clear(&self)

Removes every entry.

pub fn keys(&self) -> Vec<Value>

The keys, in insertion order (shared handles).

pub fn values(&self) -> Vec<Value>

The values, in insertion order (shared handles).

pub fn entries(&self) -> Vec<(Value, Value)>

The entries, in insertion order (shared handles).

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 groups groupby makes) 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 snapshot(&self) -> Vec<Value>

Copies the item handles (the items stay shared).

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.

pub fn item(&self, i: usize) -> Option<Value>

Item i, if there is one.

pub fn extend(&self, items: Vec<Value>)

Appends items to the end.

pub fn push(&self, item: Value)

Appends one item.

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 loop variable 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.

ForExtensions(Vec<String>)

Templates whose names end with one of these (“.html”) do, like Jinja’s select_autoescape().

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 defined and |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 Error reports.

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

impl ErrorKind
pub fn title(self) -> &'static str

The report title: “SYNTAX ERROR”, “UNDEFINED VALUE”, …

pub enum gd_jinja::Loader

A source of templates by name.

Variants

Memory(HashMap<String, String>)

Templates held in memory, by name.

Filesystem(Vec<PathBuf>)

The first of these directories that holds the name; names use “/” and may not climb out of a directory with “..”.

Custom(LoadFn)

Your own: returns the source of a name, or None when there is none.

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.

pub fn custom(f: impl Fn(&str) -> Option<String> + 'static) -> Loader

A loader calling f with each name.

pub fn load(&self, name: &str) -> Option<String>

The source of the template called name, or None when the loader has none.

Trait Implementations

impl fmt::Debug for Loader
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
pub enum gd_jinja::DictKind

What a Dict is.

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)

True or False.

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.

List(Rc<List>)

A list or a tuple.

Dict(Rc<Dict>)

A dict (ordered), a namespace or an imported module.

Callable(Rc<Callable>)

A function: native, a bound method, a macro or a block reference.

Loop(Rc<Loop>)

The loop variable of a for loop.

Cycler(Rc<Cycler>)

The object cycler() makes.

Implementations

impl Value
pub fn str(s: &str) -> Value

Makes a string 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; name is what error messages call it.

pub fn list(items: impl IntoIterator<Item = Value>) -> Value

Makes a list holding items.

pub fn tuple(items: impl IntoIterator<Item = Value>) -> Value

Makes a tuple holding items.

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 value under the string key of a dict value; nothing happens when this is not a dict.

pub fn set_key(&self, key: Value, value: Value)

Stores value under any key of a dict value.

pub fn get(&self, key: &str) -> Value

Reads a string key from a dict value; missing keys give Undefined.

pub fn keys(&self) -> Vec<String>

The string keys of a dict value, in insertion order.

pub fn push(&self, item: Value)

Appends item to 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::len is 0.

pub fn as_str(&self) -> Option<&str>

The text of a string or Markup value.

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", …).

pub fn repr(&self) -> String

The value as Python’s repr() writes it.

Trait Implementations

impl fmt::Debug for Value
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl Default for Value
fn default() -> Value

Undefined, with no details.

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

impl From<&str> for Value
fn from(s: &str) -> Value
impl From<Rc<str>> for Value
fn from(s: Rc<str>) -> Value
impl From<String> for Value
fn from(s: String) -> Value
impl From<bool> for Value
fn from(b: bool) -> Value
impl From<f64> for Value
fn from(f: f64) -> Value
impl From<i32> for Value
fn from(i: i32) -> Value
impl From<i64> for Value
fn from(i: i64) -> Value
impl PartialEq for Value
fn eq(&self, other: &Value) -> bool

Python’s ==: lists and dicts compare by content.

Functions

pub fn gd_jinja::repr(v: &Value) -> String

Converts a value as Python’s repr() does.

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 Display is 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_RECURSION levels of recursion and DEFAULT_MAX_NESTING levels 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.