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 With Arguments In minijinja

Code

//! ```cargo
//! [dependencies]
//! minijinja = "1.0.8"
//! serde = { version = "1.0.167", features = ['derive'] }
//! ```

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

#[derive(Debug, Serialize)]
struct Page {}

impl Page {
    pub fn ping(&self, args: &[Value]) -> Option<String> {
        Some(format!("Got: {}", args[0]))
    }
}

impl Object for Page {
    fn call_method(
        &self,
        _state: &minijinja::State,
        name: &str,
        args: &[Value],
    ) -> Result<Value, Error> {
        match name {
            "ping" => Ok(Value::from_serializable(&self.ping(args))),
            _ => Ok(Value::from("")),
        }
    }
}
impl Display for Page {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "required display output")
    }
}

fn main() {
    let mut env = Environment::new();
    let page = Page {};
    let page_object = Value::from_object(page);
    env.add_template("ping_test", "{{ page.ping('one') }}").unwrap();
    let tmpl = env.get_template("ping_test").unwrap();
    println!("{}", tmpl.render(context!( page => page_object )).unwrap());
}

Results

Got: one