Trait rubble_templates_core::evaluator::Function[][src]

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

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

fn evaluate(
    &self,
    evaluator: &dyn Evaluator,
    parameters: &[SyntaxNode],
    context: &mut Context
) -> Result<String, SyntaxError>
[src]

Loading content...

Implementors

impl<F> Function for FunctionWithAst<F> where
    F: Fn(&dyn Evaluator, &[SyntaxNode], &mut Context) -> Result<String, SyntaxError>, 
[src]

impl<F> Function for FunctionWithContext<F> where
    F: Fn(&[String], &mut Context) -> Result<String, SyntaxError>, 
[src]

impl<F> Function for SimpleFunction<F> where
    F: Fn(&[String]) -> String
[src]

impl<F> Function for F where
    F: Fn(&dyn Evaluator, &[SyntaxNode], &mut Context) -> Result<String, SyntaxError>, 
[src]

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 crate::functions.

Example:

use rubble_templates_core::evaluator::{Evaluator, Function, SyntaxError, Context};
use std::collections::HashMap;
use rubble_templates_core::ast::SyntaxNode;

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>
Loading content...