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.

Create A StructObject To Get Fields Directly In minijinja

  • Combine with id: 2tasgoyx

Code

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

[dependencies]
minijinja = "1.0.7"

Code

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

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_struct_object(alfa);
    println!(
        "{}",
        tmpl.render(context!(alfa_value => alfa_value)).unwrap()
    );
}

pub struct Alfa {}

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

impl Alfa {
    fn ping(&self) -> String {
        "One ping only".to_string()
    }
}