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.

Call A Function On An Object From A minijinja Template

Code

[package]
name = "minijinji_object_method_call"
version = "0.1.0"
edition = "2021"

[dependencies]
minijinja = "1.0.7"

src/main.rs

use minijinja::value::{Object, Value};
use minijinja::{context, Environment, Error};
use std::fmt::Display;

fn main() {
    let mut env = Environment::new();
    env.add_template("hello", "{{ alfa_value.ping() }}")
        .unwrap();
    let tmpl = env.get_template("hello").unwrap();
    let alfa = Alfa {};
    let alfa_value = Value::from_object(alfa);
    println!(
        "{}",
        tmpl.render(context!(alfa_value => alfa_value)).unwrap()
    );
}

#[derive(Debug)]
pub struct Alfa {}

impl Object for Alfa {
    fn call_method(
        &self,
        _state: &minijinja::State,
        name: &str,
        _args: &[Value],
    ) -> Result<Value, Error> {
        match name {
            // NOTE: May need to do: 
            // Value::from_serializable. 
            // TODO: Look into that
            "ping" => Ok(Value::from(self.ping())),
            _ => {
                // TODO: make this an error possibly
                Ok(Value::from(""))
            }
        }
    }
}

impl Display for Alfa {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "THIS IS ALFA DISPLAY DEFAULT FORMAT")
    }
}

impl Alfa {
    fn ping(&self) -> String {
        "One ping only".to_string()
    }
}
  • Switch to using Value::from_serializable as well which can be used for vecs of objects

  • Update this test with `args`` passing from call method to `ping`` via `args[0]``

References