pub trait Function {
// Required method
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§
fn evaluate( &self, evaluator: &dyn Evaluator, parameters: &[SyntaxNode], context: &mut Context, ) -> Result<String, SyntaxError>
Implementors§
impl<F> Function for FunctionWithAst<F>
impl<F> Function for FunctionWithContext<F>
impl<F> Function for SimpleFunction<F>
impl<F> Function for F
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>