Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Basic Structure For Minijinja With Multiple Templates Using A Struct In Rust

These notes may be out of date compared to the way I'm doing things now. They need to be re-vetted

Code

use minijinja::context;
use minijinja::Environment;
use minijinja::Source;
use serde::Serialize;
use std::fs;

#[derive(Debug, Serialize)]
pub struct Payload {
    data: Option<String>,
}

fn make_env<'a>(templates: Vec<(&'a str, &'a str)>) -> Environment<'a> {
    let mut env = Environment::new();
    let mut source = Source::new();
    for i in templates {
        let file_string = fs::read_to_string(i.1).unwrap();
        source.add_template(i.0, file_string).unwrap();
    }
    env.set_source(source);
    env
}

fn main() {
    let templates: Vec<(&str, &str)> =
        vec![("example", "src/bin/minijinja_structure_template.html")];
    let payload = Payload {
        data: Some("Minijinja".to_string()),
    };
    let env = make_env(templates);
    let output = render_template(payload, env);
    dbg!(output);
}

fn render_template(payload: Payload, env: Environment) -> String {
    let tmpl = env.get_template("example").unwrap();
    tmpl.render(context!(payload => &payload))
        .unwrap()
        .to_string()
}

This uses `Source::new()`rust` to get the templates instead of `.add_template()`rust on an `Environment::new()`rust becuase that doesn't work if you try to use it in a different function.