Render A Basic Template From JSON Data With MiniJinja In Rust

March 2023

This is a quick example showing how to take a string of JSON and use it as data to populate a MiniJinja template.

---
[dependencies]
minijinja = { version = "2.9.0" }
serde_json = "1.0.111"
---

use minijinja::Environment;
use serde_json::Value;

fn main() {
    // let json = fs::read_to_string("src/data.json").unwrap();
    let json = r#"{ "name": "World" }"#.to_string();

    // let template = fs::read_to_string("src/templates/mixer.html").unwrap();
    let template = r#"<h1>Hello, {{ name }}</h1>"#.to_string();

    let output = render_template(template, json);
    println!("{}", output);
}

fn render_template(template: String, json: String) -> String {
    let data: Value = serde_json::from_str(json.as_str()).unwrap();
    let mut env = Environment::new();
    env.add_template("template", template.as_str()).unwrap();
    let tmpl = env.get_template("template").unwrap();
    tmpl.render(data).unwrap().to_string()
}
Output:
<h1>Hello, World</h1>

Notes

  • The example has lines for using files as input that have been commented out in favor of inline Strings. This makes the example directly runnable without dependencies.
  • The two creates that were added for this are minijinja and serde_json
end of line