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.

How - to Call Methods On Structs In MiniJinja

My mental model of template languages is to serialize content and send it down the pipe for rendering. I was spending a lot of time working through that on my site realized that shouldn't be necessary.

Sure enough MiniJinja has a [TODO: Code shorthand span ] that lets you call methods to generate content dynamically during rendering. It's super useful. No more trying to parse data then rebuild it for easy access. I'm just going to send a single object down with the entire data set and use methods to parse out what I need.

Here's what it looks like :

rust
use minijinja::value::{StructObject, Value};
use minijinja::Environment;

pub struct Universe;

impl Universe {
    fn ping(&self) -> String {
        "CONNECTED".to_string()
    }
}

impl StructObject for Universe {
    fn get_field(&self, field: &str) -> Option<Value> {
        match field {
            "ping" => Some(Value::from(self.ping())),
            _ => None,
        }
    }
}

fn main() {
    let alfa = Universe;
    let env = Environment::new();
    let tmpl = env.template_from_str(
      "Check: {{ ping }}"
    ).unwrap();
    let ctx = Value::from_struct_object(alfa);
    let rv = tmpl.render(ctx).unwrap();
    dbg!(rv);
}

Footnotes And References