gd_jinja ======== .. rust:crate:: gd_jinja :synopsis: gd-jinja: a standalone Jinja 3.x template engine. 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. .. code-block:: rust 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("")); let out = env.render_str("Hello {{ name }}!", &ctx).unwrap(); assert_eq!(out, "Hello <World>!"); Every failure is an :rust:struct:`Error ` whose ``Display`` is the Elm-style report; nothing panics on bad templates or data. See the crate README for the cheat sheet. .. rubric:: Structs .. rust:struct:: pub struct 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. .. rubric:: Fields .. rust:field:: pub args: Vec Positional arguments. .. rust:field:: pub kwargs: Vec Keyword arguments, in the order given. .. rust:field:: pub this: Value The receiver of a bound method; Undefined otherwise. .. rust:field:: pub name: Rc The name the procedure was registered or looked up by. .. rubric:: Implementations .. rust:impl:: impl<'a, 'env> Call<'a, 'env> :noindex: :for: Call<'a, 'env> .. rust:method:: pub fn arg(&self, index: usize, name: &str) -> Value Positional argument ``index``, else the keyword argument ``name``, else Undefined. .. rust:method:: pub fn arg_or(&self, index: usize, name: &str, default: Value) -> Value Positional argument ``index``, else the keyword argument ``name``, else ``default``. .. rust:method:: pub fn keyword(&self, name: &str) -> Option The keyword argument ``name``, if it was passed. .. rust:method:: pub fn has_arg(&self, index: usize, name: &str) -> bool Whether the argument was passed at all. .. rust:method:: 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. .. rust:method:: pub fn arg_int(&self, index: usize, name: &str, default: i64) -> std::result::Result An integer argument; bools and floats are accepted, and None gives ``default``. .. rust:method:: pub fn arg_count(&self, index: usize, name: &str, default: i64) -> std::result::Result Like :rust:fn:`Call::arg_int `, with negative values read as 0. .. rust:method:: 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. .. rust:method:: pub fn error(&self, message: &str) -> Error An error at the place the call happens, for the procedure to return. .. rust:method:: pub fn autoescaping(&self) -> bool Whether autoescape is on where the call happens. .. rust:method:: pub fn call_filter(&mut self, name: &str, args: Vec, kwargs: Vec) -> std::result::Result Runs a registered filter by name. .. rust:method:: pub fn call_test(&mut self, name: &str, args: Vec, kwargs: Vec) -> std::result::Result Runs a registered test by name. .. rubric:: Trait Implementations .. rust:impl:: impl std::fmt::Debug for Call<'_, '_> :noindex: :for: Call<'_, '_> :trait: std::fmt::Debug .. rust:method:: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result :noindex: .. rust:struct:: pub struct Keyword One keyword argument of a call. .. rubric:: Fields .. rust:field:: pub name: Rc The parameter name. .. rust:field:: pub value: Value The value passed. .. rust:struct:: pub struct Environment Options, filters, tests, globals and the template cache. An environment is not thread-safe; use one per thread. .. rubric:: Fields .. rust:field:: pub options: Options The options it was made with. .. rubric:: Implementations .. rust:impl:: impl Environment :noindex: :for: Environment .. rust:method:: pub fn new(options: Options) -> Environment Makes an environment with the built-in filters, tests and globals. .. rust:method:: pub fn add_filter(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'static) Registers a filter: ``call.args[0]`` is the filtered value. .. rust:method:: pub fn add_test(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'static) Registers a test: ``call.args[0]`` is the tested value; its truthiness is the answer. .. rust:method:: pub fn add_global(&mut self, name: &str, value: Value) Makes a value visible to every template. .. rust:method:: pub fn add_function(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'static) Registers a native procedure as a global function. .. rust:method:: pub fn clear_cache(&self) Forgets parsed templates, so the next load reads them again. .. rust:method:: pub fn take_template_loads(&self) -> Vec Takes the names requested since the last call, sorted and deduplicated. Includes cached templates and missing names, including ``ignore missing`` lookups. .. rust:method:: pub fn load_template(&self, name: &str) -> Result, Error> Loads a template through the loader, cached until clear_cache. .. rust:method:: pub fn parse_template(&self, name: &str, source: &str) -> Result, Error> Parses source as a template called name; it is not cached, so extends and include do not find it (see add_template). .. rust:method:: 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. .. rust:method:: pub fn render_str(&self, source: &str, ctx: &Value) -> Result Parses and renders source once, caching nothing. ``ctx`` is a dict value, or Undefined for none. .. rust:method:: pub fn render_str_with(&self, source: &str, ctx: &Value, locals: &Locals<'_>) -> Result 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. .. rust:method:: pub fn evaluate(&self, expression: &str, ctx: &Value) -> Result Evaluates one expression against ctx (Jinja's ``compile_expression``). .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Environment :noindex: :for: Environment :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl Default for Environment :noindex: :for: Environment :trait: Default .. rust:method:: fn default() -> Environment :noindex: .. rust:struct:: pub struct Options Plain options; fill the ones you need with struct-update syntax: ``Options { autoescape: Autoescape::Always, ..Options::default() }``. .. rubric:: Fields .. rust:field:: pub autoescape: Autoescape Which templates escape their output. .. rust:field:: pub trim_blocks: bool Drop the first newline after a block tag. .. rust:field:: pub lstrip_blocks: bool Strip spaces and tabs before a block tag at the start of a line. .. rust:field:: pub keep_trailing_newline: bool Keep the source's final newline. .. rust:field:: pub undefined: UndefinedMode How undefined values behave. .. rust:field:: pub loader: Option Where ``load_template``, ``extends``, ``include`` and ``import`` read from. .. rust:field:: pub max_recursion: usize How deep macros, includes, blocks and recursive loops may nest. .. rust:field:: pub max_iterations: usize Loop iterations (and ``range()`` sizes) per render. .. rust:field:: 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. .. rust:field:: pub max_nesting: usize How deep template syntax nests: brackets, tags, and operator, filter, attribute and elif chains. .. rust:field:: 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. .. rust:field:: pub random_seed: u64 Seeds ``random`` and ``lipsum``; 0 picks a fixed seed. Renders are deterministic. .. rubric:: Trait Implementations .. rust:impl:: impl Default for Options :noindex: :for: Options :trait: Default .. rust:method:: fn default() -> Options :noindex: .. rust:struct:: pub struct Template<'env> A parsed template, ready to render. It borrows its environment. .. rubric:: Implementations .. rust:impl:: impl Template<'_> :noindex: :for: Template<'_> .. rust:method:: pub fn name(&self) -> &str The template's name. .. rust:method:: pub fn render(&self, ctx: &Value) -> Result Renders the template with ctx (a dict value, or Undefined for none). .. rust:method:: pub fn render_with(&self, ctx: &Value, locals: &Locals<'_>) -> Result 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. .. rust:struct:: pub struct 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: .. code-block:: text -- UNDEFINED VALUE -------------------------------------------------- page.html:3 'usr' is undefined 3|

{{ usr.name }}

Hint: Did you mean 'user'? .. rubric:: Fields .. rust:field:: pub kind: ErrorKind What kind of failure this is. .. rust:field:: pub template: String The template's name; empty when there is none. .. rust:field:: pub line: usize The 1-based line, or 0 when unknown. .. rust:field:: pub message: String The plain explanation. .. rust:field:: pub excerpt: String The text of the line the error points at. .. rust:field:: pub hint: String How to fix it; empty when there is no suggestion. .. rubric:: Implementations .. rust:impl:: impl Error :noindex: :for: Error .. rust:method:: pub fn new(kind: ErrorKind, line: usize, message: impl Into) -> Error Makes an error of kind with message; the render that returns it fills in where. .. rust:method:: pub fn with_hint(mut self, hint: impl Into) -> Error Returns the error with ``hint`` attached, unless it already has one. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Display for Error :noindex: :for: Error :trait: fmt::Display .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl std::error::Error for Error :noindex: :for: Error :trait: std::error::Error .. rust:impl:: impl From> for Error :noindex: :for: Error :trait: From> .. rust:method:: fn from(err: Box) -> Error :noindex: .. rust:struct:: pub struct Locals<'a> The functions and filters one render adds to its environment's. .. code-block:: rust 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"); .. rubric:: Implementations .. rust:impl:: impl<'a> Locals<'a> :noindex: :for: Locals<'a> .. rust:method:: pub fn new() -> Locals<'a> No functions or filters. .. rust:method:: pub fn add_function(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'a) -> &mut Locals<'a> Adds a function called ``name``, replacing one added before under that name. .. rust:method:: pub fn add_filter(&mut self, name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'a) -> &mut Locals<'a> Adds a filter called ``name`` (``call.args[0]`` is the value filtered), replacing one added before under that name. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Locals<'_> :noindex: :for: Locals<'_> :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:struct:: pub struct State<'env> One render in progress. Native procedures reach it through :rust:struct:`crate::Call `. .. rubric:: Trait Implementations .. rust:impl:: impl std::fmt::Debug for State<'_> :noindex: :for: State<'_> :trait: std::fmt::Debug .. rust:method:: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result :noindex: .. rust:struct:: pub struct Callable A function value. .. rubric:: Implementations .. rust:impl:: impl Callable :noindex: :for: Callable .. rust:method:: pub fn name(&self) -> &str The name the function was registered or defined with. .. rust:method:: pub fn is_macro(&self) -> bool Whether this is a macro (or a call block's ``caller``). .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Callable :noindex: :for: Callable :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:struct:: pub struct Cycler The object made by the ``cycler()`` global. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Cycler :noindex: :for: Cycler :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:struct:: pub struct Dict An insertion-ordered dictionary. String keys are indexed; other keys are compared with Python equality (``1 == 1.0 == True``). .. rubric:: Implementations .. rust:impl:: impl Dict :noindex: :for: Dict .. rust:method:: pub fn new(kind: DictKind) -> Rc Makes an empty shared dict of ``kind``. .. rust:method:: pub fn begin_key_trace(&self) Starts recording string-key reads, including missing keys. Replaces any prior trace. .. rust:method:: pub fn end_key_trace(&self) -> Vec Stops recording and returns distinct keys in sorted order; empty if tracing was off. .. rust:method:: pub fn kind(&self) -> DictKind What the dict is. .. rust:method:: pub fn name(&self) -> &str The template name of a module; empty otherwise. .. rust:method:: pub fn len(&self) -> usize The number of entries. .. rust:method:: pub fn is_empty(&self) -> bool Whether the dict has no entries. .. rust:method:: pub fn get(&self, key: &Value) -> Option The value stored under ``key``. .. rust:method:: pub fn get_str(&self, key: &str) -> Option The value stored under the string ``key``. .. rust:method:: pub fn set(&self, key: Value, value: Value) Adds or replaces an entry. .. rust:method:: pub fn remove(&self, key: &Value) -> Option Removes the entry under ``key`` and returns its value. .. rust:method:: pub fn clear(&self) Removes every entry. .. rust:method:: pub fn keys(&self) -> Vec The keys, in insertion order (shared handles). .. rust:method:: pub fn values(&self) -> Vec The values, in insertion order (shared handles). .. rust:method:: pub fn entries(&self) -> Vec<(Value, Value)> The entries, in insertion order (shared handles). .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Dict :noindex: :for: Dict :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl Drop for Dict :noindex: :for: Dict :trait: Drop .. rust:method:: fn drop(&mut self) :noindex: .. rust:struct:: pub struct List A list, or a tuple when ``is_tuple``. A named tuple (the groups ``groupby`` makes) can also be read through its field names. .. rubric:: Implementations .. rust:impl:: impl List :noindex: :for: List .. rust:method:: pub fn new(items: Vec, tuple: bool) -> Rc Makes a shared list (or tuple) holding ``items``. .. rust:method:: pub fn items(&self) -> Ref<'_, Vec> 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. .. rust:method:: pub fn snapshot(&self) -> Vec Copies the item handles (the items stay shared). .. rust:method:: pub fn len(&self) -> usize The number of items. .. rust:method:: pub fn is_empty(&self) -> bool Whether the list has no items. .. rust:method:: pub fn is_tuple(&self) -> bool Whether this is a tuple. .. rust:method:: pub fn item(&self, i: usize) -> Option Item ``i``, if there is one. .. rust:method:: pub fn extend(&self, items: Vec) Appends items to the end. .. rust:method:: pub fn push(&self, item: Value) Appends one item. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for List :noindex: :for: List :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl Drop for List :noindex: :for: List :trait: Drop .. rust:method:: fn drop(&mut self) :noindex: .. rust:struct:: pub struct Loop The special ``loop`` variable of a for loop. .. rubric:: Implementations .. rust:impl:: impl Loop :noindex: :for: Loop .. rust:method:: pub fn index0(&self) -> usize The 0-based index of the current iteration. .. rust:method:: pub fn len(&self) -> usize The number of items the loop runs over. .. rust:method:: pub fn is_empty(&self) -> bool Whether the loop runs over no items. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Loop :noindex: :for: Loop :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:struct:: pub struct 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. .. rubric:: Fields .. rust:field:: pub name: Rc The missing variable or attribute. .. rust:field:: pub owner: Rc ``"dict object"`` when an attribute or item was missing, else empty. .. rust:field:: pub hint: Rc A complete message that replaces the generated one, or empty. .. rubric:: Enums .. rust:enum:: pub enum Autoescape Which templates HTML-escape the ``{{ }}`` output that is not Markup. .. rubric:: Variants .. rust:variant:: Never No template does. .. rust:variant:: Always Every template does. .. rust:variant:: ForExtensions(Vec) Templates whose names end with one of these (".html") do, like Jinja's ``select_autoescape()``. .. rust:enum:: pub enum UndefinedMode How undefined values behave, like Jinja's Undefined classes. .. rubric:: Variants .. rust:variant:: Default Renders as "", fails on attribute access, calls and arithmetic. .. rust:variant:: Strict Fails on every use except ``is defined`` and ``|default``. .. rust:variant:: Chainable Like Default, but attributes of undefined values are undefined too. .. rust:variant:: Debug Like Default, but renders as ``{{ name }}``. .. rust:enum:: pub enum ErrorKind What kind of failure an :rust:struct:`Error ` reports. .. rubric:: Variants .. rust:variant:: Syntax The template does not parse (Jinja's TemplateSyntaxError). .. rust:variant:: Undefined An undefined value was used (UndefinedError). .. rust:variant:: Type An operation got the wrong kind of value (TypeError). .. rust:variant:: NotFound A template could not be loaded (TemplateNotFound). .. rust:variant:: Limit A recursion, nesting, iteration, output or stack limit was reached. .. rust:variant:: Memory A value too large to count or to allocate was asked for (MemoryError). .. rust:variant:: Runtime Any other failure while rendering. .. rubric:: Implementations .. rust:impl:: impl ErrorKind :noindex: :for: ErrorKind .. rust:method:: pub fn title(self) -> &'static str The report title: "SYNTAX ERROR", "UNDEFINED VALUE", ... .. rust:enum:: pub enum Loader A source of templates by name. .. rubric:: Variants .. rust:variant:: Memory(HashMap) Templates held in memory, by name. .. rust:variant:: Filesystem(Vec) The first of these directories that holds the name; names use "/" and may not climb out of a directory with "..". .. rust:variant:: Custom(LoadFn) Your own: returns the source of a name, or None when there is none. .. rubric:: Implementations .. rust:impl:: impl Loader :noindex: :for: Loader .. rust:method:: pub fn memory, S: Into>(sources: impl IntoIterator) -> Loader A loader serving the given (name, source) pairs. .. rust:method:: pub fn filesystem>(directories: impl IntoIterator) -> Loader A loader reading from directories, searched in order. .. rust:method:: pub fn custom(f: impl Fn(&str) -> Option + 'static) -> Loader A loader calling f with each name. .. rust:method:: pub fn load(&self, name: &str) -> Option The source of the template called name, or None when the loader has none. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Loader :noindex: :for: Loader :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:enum:: pub enum DictKind What a :rust:struct:`Dict ` is. .. rubric:: Variants .. rust:variant:: Dict A plain dict. .. rust:variant:: Namespace ``namespace()``: the only object whose attributes templates may assign. .. rust:variant:: Module The result of ``{% import %}``: exported macros and variables. .. rust:enum:: pub enum 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. .. rubric:: Variants .. rust:variant:: Undefined(Option>) A missing value, with the details its error message names when there are any. .. rust:variant:: None Python's ``None``. .. rust:variant:: Bool(bool) ``True`` or ``False``. .. rust:variant:: Int(i64) A 64-bit integer; overflow is an error, not a wrap. .. rust:variant:: Float(f64) A float. .. rust:variant:: Str(Rc) A string. .. rust:variant:: Markup(Rc) A string that is already safe HTML: autoescaping leaves it alone. .. rust:variant:: List(Rc) A list or a tuple. .. rust:variant:: Dict(Rc) A dict (ordered), a namespace or an imported module. .. rust:variant:: Callable(Rc) A function: native, a bound method, a macro or a block reference. .. rust:variant:: Loop(Rc) The ``loop`` variable of a for loop. .. rust:variant:: Cycler(Rc) The object ``cycler()`` makes. .. rubric:: Implementations .. rust:impl:: impl Value :noindex: :for: Value .. rust:method:: pub fn str(s: &str) -> Value Makes a string value. .. rust:method:: pub fn markup(s: &str) -> Value Makes a string value that is safe HTML, which autoescaping leaves alone. .. rust:method:: pub fn undefined(name: &str) -> Value Makes an undefined value; ``name`` is what error messages call it. .. rust:method:: pub fn list(items: impl IntoIterator) -> Value Makes a list holding ``items``. .. rust:method:: pub fn tuple(items: impl IntoIterator) -> Value Makes a tuple holding ``items``. .. rust:method:: pub fn dict() -> Value Makes an empty dict; fill it with :rust:fn:`Value::set `. .. rust:method:: pub fn function(name: &str, f: impl Fn(&mut Call<'_, '_>) -> Result + 'static) -> Value Wraps a native procedure as a callable value for globals or context data. .. rust:method:: 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. .. rust:method:: pub fn set_key(&self, key: Value, value: Value) Stores ``value`` under any key of a dict value. .. rust:method:: pub fn get(&self, key: &str) -> Value Reads a string key from a dict value; missing keys give Undefined. .. rust:method:: pub fn keys(&self) -> Vec The string keys of a dict value, in insertion order. .. rust:method:: pub fn push(&self, item: Value) Appends ``item`` to a list value; nothing happens when this is not a list. .. rust:method:: pub fn len(&self) -> usize The number of items of a list or dict, or of characters of a string; 0 otherwise. .. rust:method:: pub fn is_empty(&self) -> bool Whether :rust:fn:`Value::len ` is 0. .. rust:method:: pub fn as_str(&self) -> Option<&str> The text of a string or Markup value. .. rust:method:: pub fn is_undefined(&self) -> bool Whether the value is undefined. .. rust:method:: pub fn is_none(&self) -> bool Whether the value is None. .. rust:method:: pub fn is_markup(&self) -> bool Whether the value is safe HTML. .. rust:method:: pub fn is_string(&self) -> bool Whether the value is a string or Markup. .. rust:method:: pub fn is_truthy(&self) -> bool Python truthiness (Undefined is false). .. rust:method:: pub fn type_name(&self) -> &'static str The Python type name used in Jinja's error messages (``"str"``, ``"dict"``, ...). .. rust:method:: pub fn repr(&self) -> String The value as Python's ``repr()`` writes it. .. rubric:: Trait Implementations .. rust:impl:: impl fmt::Debug for Value :noindex: :for: Value :trait: fmt::Debug .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: .. rust:impl:: impl Default for Value :noindex: :for: Value :trait: Default .. rust:method:: fn default() -> Value :noindex: Undefined, with no details. .. rust:impl:: impl fmt::Display for Value :noindex: :for: Value :trait: fmt::Display .. rust:method:: fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result :noindex: Writes the value as Python's ``str()`` does (Undefined writes nothing). .. rust:impl:: impl From<&str> for Value :noindex: :for: Value :trait: From<&str> .. rust:method:: fn from(s: &str) -> Value :noindex: .. rust:impl:: impl From> for Value :noindex: :for: Value :trait: From> .. rust:method:: fn from(s: Rc) -> Value :noindex: .. rust:impl:: impl From for Value :noindex: :for: Value :trait: From .. rust:method:: fn from(s: String) -> Value :noindex: .. rust:impl:: impl From for Value :noindex: :for: Value :trait: From .. rust:method:: fn from(b: bool) -> Value :noindex: .. rust:impl:: impl From for Value :noindex: :for: Value :trait: From .. rust:method:: fn from(f: f64) -> Value :noindex: .. rust:impl:: impl From for Value :noindex: :for: Value :trait: From .. rust:method:: fn from(i: i32) -> Value :noindex: .. rust:impl:: impl From for Value :noindex: :for: Value :trait: From .. rust:method:: fn from(i: i64) -> Value :noindex: .. rust:impl:: impl PartialEq for Value :noindex: :for: Value :trait: PartialEq .. rust:method:: fn eq(&self, other: &Value) -> bool :noindex: Python's ``==``: lists and dicts compare by content. .. rubric:: Functions .. rust:function:: pub fn repr(v: &Value) -> String Converts a value as Python's ``repr()`` does. .. rust:function:: pub fn 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. .. rust:function:: pub fn 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()``). .. rust:function:: pub fn escape_string(s: &str) -> Cow<'_, str> Replaces the five HTML special characters as MarkupSafe does; text that has none is borrowed. .. rust:function:: pub fn render_str(source: &str, ctx: &Value) -> Result Renders source once with ctx (a dict value, or Undefined for none) in a default environment: the one-call path. .. rubric:: Errors Returns the parse or render error, whose ``Display`` is an Elm-style report. .. rubric:: Type Aliases .. rust:type:: pub type LoadFn = Rc Option> A procedure returning the source of a template by name, or None. .. rust:type:: pub type LocalFn<'a> = dyn Fn(&mut Call<'_, '_>) -> Result + 'a A native procedure of one render; it may borrow data that lives for ``'a``. .. rust:type:: pub type Native = Rc) -> Result> The one signature of every filter, test, global function and method written in Rust. Report errors by returning ``Err(call.error("..."))``. .. rubric:: Constants .. rust:const:: pub const MAX_VALUE_DEPTH: usize = 200 How deep repr, equality, ordering and tojson follow nested lists and dicts. .. rust:const:: pub const DEFAULT_MAX_NESTING: usize = 100 How deep a template's syntax may nest by default. .. rust:const:: pub const DEFAULT_MAX_RECURSION: usize = 200 How deep macros, includes, blocks and recursive loops may nest by default. .. rust:const:: pub const 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.