Render A Basic Template From JSON Data With MiniJinja In Rust

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

use minijinja::Environment;
use serde_json::Value;
use std::fs;

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()"#.to_string();

    let output = render_template(template, json);

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();
  • 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``