home ~ projects ~ socials

Change MiniJinja's Template Token Syntax For Functions, Values, and Comments

This is how I'm changing the template tokens in minijinja to make them easier for me to read. In this example, I'm converting to using these tokens:

```cargo
[dependencies]
minijinja = { version = "2.0.2", features = ["custom_syntax", "loader"] }
```

use minijinja::{Environment, context};
use minijinja::syntax::SyntaxConfig;

fn main() {
    let mut env = Environment::new();
    env.set_syntax(
        SyntaxConfig::builder()
            .block_delimiters("[!", "!]")
            .variable_delimiters("[@", "@]")
            .comment_delimiters("[#", "#]")
            .build()
            .unwrap(),
    );
    env.add_template_owned(
        "hello", "Hello [@ name @]!".to_string()
    ).unwrap();
    let skeleton = env.get_template("hello").unwrap();
    let output = skeleton.render(context!(name => "World")).unwrap();
    println!("{}", output);
}
Output:
Hello World!
[! !]   [@ @]   [# #]

Instead of

{% %}   {{ }}   {# #}

I find those easier to type and to read.

Notes

  • Setting the syntax requires the "custom_syntax" feature in the cargo dependencies
  • I'm also using the "loader" feature to allow loading Strings via .add_template_owned(). That's not necessary for the syntax change. It's my preferred method since it avoids having to worry about lifetimes so I've been using it for all my notes.
-- end of line --

References