bracket/helper/
if.rs

1//! Helpers for conditional statements.
2use crate::{
3    helper::{Helper, HelperValue},
4    parser::ast::Node,
5    render::{Context, Render},
6};
7
8use serde_json::Value;
9
10/// Evaluates an argument as *truthy*.
11///
12/// For block execution if the value is *truthy* the inner template
13/// is rendered otherwise each conditional is evaluated and
14/// the first one which returns a *truthy* value is rendered.
15///
16/// When executed in a statement this helper returns whether it's
17/// argument is *truthy*.
18///
19pub struct If;
20
21impl Helper for If {
22    fn call<'render, 'call>(
23        &self,
24        rc: &mut Render<'render>,
25        ctx: &Context<'call>,
26        template: Option<&'render Node<'render>>,
27    ) -> HelperValue {
28        ctx.arity(1..1)?;
29
30        if let Some(template) = template {
31            if ctx.is_truthy(ctx.get(0).unwrap()) {
32                rc.template(template)?;
33            } else if let Some(node) = rc.inverse(template)? {
34                rc.template(node)?;
35            }
36            Ok(None)
37        } else {
38            Ok(Some(Value::Bool(ctx.is_truthy(ctx.get(0).unwrap()))))
39        }
40    }
41}