Crate minijinja[][src]

Expand description

MiniJinja is a simple Jinja2 inspired template engine based on serde. It’s light in features and on dependencies but implements a pretty sizable feature set from Jinja2. It attempts to stay largely compatible in Syntax and behavior:

{% for user in users %}
  <li>{{ user.name }}</li>
{% endfor %}

Why MiniJinja

Rust already has quite a selection of template engines and there are in fact already a handful of engines which are inspired by Jinja2 including Tera and Askama but they are very heavy in terms of dependencies and usage. MiniJinja by its name does not try to become a replacement for these, but it wants to be a good default choice if you need a little bit of templating with minimal dependencies.

MiniJinja tries to juggle these three goals:

  1. aim for a high level of compatibility with Jinja2 templates
  2. provide template rendering and expression evaluation functionality
  3. achieve above functionality with the lest amount of dependencies possible

Template Usage

To use MiniJinja one needs to create an Environment and pupulate it with templates. Afterwards templates can be loaded and rendered. To pass data one can pass any serde serializable value:

use std::collections::BTreeMap;
use minijinja::Environment;

let mut env = Environment::new();
env.add_template("hello", "Hello {{ name }}!").unwrap();
let mut ctx = BTreeMap::new();
ctx.insert("name", "John");
println!("{}", env.get_template("hello").unwrap().render(&ctx).unwrap());

Expression Usage

MiniJinja — like Jinja2 — allows to be used as expression language. This can be useful to express logic in configuration files or similar things. For this purpose the Environment::compile_expression method can be used. It returns an expression object that can then be evaluate and the result is returned:

use std::collections::BTreeMap;
use minijinja::Environment;

let env = Environment::new();
let expr = env.compile_expression("23 < 42").unwrap();
let result = expr.eval(&()).unwrap();
assert_eq!(result.is_true(), true);

Modules

Built in filters and filter abstraction.

Built in tests and test abstraction.

Provides a dynamic value type abstraction.

Structs

An abstraction that holds the engine configuration.

Represents template errors.

A handle to a compiled expression.

Represents a handle to a template.

Enums

Controls the autoescaping behavior.

An enum describing the error kind.