Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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

- Look at 2as2evj4 for loading templates from a directory

This works for specific, individual templates. I generally load an entire directory so I use > this instead > 2ofddkppv9ik > as my goto

rust
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() [TODO: Code shorthand span ] 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.