Skip to content

custom salt-like function syntax: function['module.method']('parameter') ? #668

Answered by mitsuhiko
LinuxSquare asked this question in Q&A
Discussion options

You must be logged in to vote

env.add_function is just an alias for env.add_global with Value::from_function. This means you can just create a map and assign a value to it:

use std::collections::BTreeMap;

use minijinja::{Environment, Value};

fn file_exists(filename: &str) -> bool {
    std::fs::metadata(filename).map_or(false, |x| x.is_file())
}

fn main() {
    let mut env = Environment::new();
    let salt_module = BTreeMap::from([(
        "file.file_exists".to_string(),
        Value::from_function(file_exists),
    )]);
    env.add_global("salt", Value::from_object(salt_module));
    env.add_template(
        "test.txt",
        "File exists: {{ salt['file.file_exists']('src/main.rs') }}",
    )
    .unwrap();

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@LinuxSquare
Comment options

@mitsuhiko
Comment options

@LinuxSquare
Comment options

Answer selected by mitsuhiko
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants