home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

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 StructObject 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:

July 2023
Code
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