oxblade 0.2.0

Laravel Blade templates for Rust: Blade's markup and directives with Rust expressions, rendering the same HTML as Laravel. Community package, not affiliated with Laravel.
Documentation
use std::rc::Rc;

use crate::value::{Object, Value};

const FIELDS: [&str; 10] = [
    "index",
    "iteration",
    "remaining",
    "count",
    "first",
    "last",
    "even",
    "odd",
    "depth",
    "parent",
];

#[derive(Clone, Debug)]
enum Parent<'a> {
    Loop(Rc<LoopState<'a>>),
    Value(Rc<Value<'a>>),
}

/// Loop metadata stays in the iteration frame until it is read.
#[derive(Clone, Debug)]
pub(crate) struct LoopState<'a> {
    index: usize,
    count: usize,
    depth: i64,
    parent: Option<Parent<'a>>,
}

impl<'a> LoopState<'a> {
    pub(crate) const FIELD_COUNT: usize = FIELDS.len();

    pub(crate) fn from_parent(parent: Value<'a>) -> Self {
        let depth = match parent.field("depth") {
            Some(Value::Int(depth)) => depth.saturating_add(1),
            _ => 1,
        };
        Self {
            depth,
            parent: (!matches!(parent, Value::Null)).then(|| Parent::Value(Rc::new(parent))),
            index: 0,
            count: 0,
        }
    }

    pub(crate) fn child(&self) -> Self {
        Self {
            depth: self.depth.saturating_add(1),
            parent: Some(Parent::Loop(Rc::new(self.clone()))),
            index: 0,
            count: 0,
        }
    }

    pub(crate) fn iteration(&self, index: usize, count: usize) -> Self {
        Self {
            index,
            count,
            ..self.clone()
        }
    }

    pub(crate) fn materialize(&self) -> Value<'a> {
        Value::Map(
            FIELDS
                .into_iter()
                .filter_map(|name| self.field(name).map(|value| (name.to_owned(), value)))
                .collect(),
        )
    }
}

impl<'a> Object<'a> for LoopState<'a> {
    fn type_name(&self) -> &'static str {
        "map"
    }

    fn field(&self, name: &str) -> Option<Value<'a>> {
        Some(match name {
            "index" => Value::Int(self.index as i64),
            "iteration" => Value::Int(self.index as i64 + 1),
            "remaining" => Value::Int(self.count.saturating_sub(self.index + 1) as i64),
            "count" => Value::Int(self.count as i64),
            "first" => Value::Bool(self.index == 0),
            "last" => Value::Bool(self.index + 1 == self.count),
            "even" => Value::Bool(!self.index.is_multiple_of(2)),
            "odd" => Value::Bool(self.index.is_multiple_of(2)),
            "depth" => Value::Int(self.depth),
            "parent" => match &self.parent {
                Some(Parent::Loop(parent)) => parent.materialize(),
                Some(Parent::Value(parent)) => parent.as_ref().clone(),
                None => Value::Null,
            },
            _ => return None,
        })
    }
}