Trait rubble_templates::evaluator::Function[][src]

pub trait Function {
    fn evaluate(
        &self,
        evaluator: &dyn Evaluator,
        parameters: &[SyntaxNode],
        context: &mut Context
    ) -> Result<String, SyntaxError>; }
Expand description

A function that can be used to add features to the template.

Any struct that implements this trait adds additional features that can additional function which will be available to anyone using given Evaluator that has it installed.

For example, you might implement custom function for date parsing etc etc.

During evaluation, an original Evaluator will be supplied to enable parameter evaluation. Parameter evaluation with a supplied Evaluator is optional and a given Function can evaluate them independently.

Required methods

Implementors

Impl for Function that allows to use lambda as a function in Evaluator.

Allows to use Fn(&dyn Evaluator, &[SyntaxNode], &mut Context) -> Result<String, SyntaxError> as Function in Evaluator. For other implementations, see functions.

Example:

use rubble_templates::evaluator::{Evaluator, Function, SyntaxError, Context};
use rubble_templates::evaluator::ast::SyntaxNode;
use rubble_templates::template::Template;
use rubble_templates::compile_template_from_string;
use std::collections::HashMap;

fn plus_function(evaluator: &dyn Evaluator, parameters: &[SyntaxNode], context: &mut Context) -> Result<String, SyntaxError> {
    Ok(
        parameters.iter()
            .map(|node|
                evaluator.evaluate(node, context).unwrap().parse::<i32>().unwrap()
            )
            .sum::<i32>()
            .to_string()
    )
}

let mut functions: HashMap<String, Box<dyn Function>> = HashMap::new();
functions.insert("plus".to_string(), Box::new(plus_function)); // will be treated as Box<dyn Function>

let variables: HashMap<String, String> = HashMap::new();

let result = compile_template_from_string("2 + 2 = {{ plus 2 2 }}".to_string(), variables, functions);
assert_eq!(result.ok(), Some("2 + 2 = 4".to_string()));