From f1422f5c66509f251e1e3e2cbd1752131dd1301f Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Sat, 23 Jun 2018 17:07:45 +0200 Subject: Add support for Index operation (see #95) --- askama_derive/src/generator.rs | 9 +++++++++ askama_derive/src/parser.rs | 17 ++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs index 59d8134..0e86a27 100644 --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -594,6 +594,7 @@ impl<'a> Generator<'a> { Expr::Path(ref path) => self.visit_path(path, code), Expr::Array(ref elements) => self.visit_array(elements, code), Expr::Attr(ref obj, name) => self.visit_attr(obj, name, code), + Expr::Index(ref obj, ref key) => self.visit_index(obj, key, code), Expr::Filter(name, ref args) => self.visit_filter(name, args, code), Expr::Unary(op, ref inner) => self.visit_unary(op, inner, code), Expr::BinOp(op, ref left, ref right) => self.visit_binop(op, left, right, code), @@ -728,6 +729,14 @@ impl<'a> Generator<'a> { DisplayWrap::Unwrapped } + fn visit_index(&mut self, obj: &Expr, key: &Expr, code: &mut String) -> DisplayWrap { + self.visit_expr(obj, code); + code.push_str("["); + self.visit_expr(key, code); + code.push_str("]"); + DisplayWrap::Unwrapped + } + fn visit_method_call( &mut self, obj: &Expr, diff --git a/askama_derive/src/parser.rs b/askama_derive/src/parser.rs index 96e0f09..c8bbb96 100644 --- a/askama_derive/src/parser.rs +++ b/askama_derive/src/parser.rs @@ -12,6 +12,7 @@ pub enum Expr<'a> { Path(Vec<&'a str>), Array(Vec>), Attr(Box>, &'a str), + Index(Box>, Box>), Filter(&'a str, Vec>), Unary(&'a str, Box>), BinOp(&'a str, Box>, Box>), @@ -347,6 +348,20 @@ named!(expr_attr, do_parse!( }) )); +named!(expr_index, do_parse!( + obj: expr_attr >> + key: opt!(do_parse!( + ws!(tag_s!("[")) >> + key: expr_any >> + ws!(tag_s!("]")) >> + (key) + )) >> + (match key { + Some(key) => Expr::Index(Box::new(obj), Box::new(key)), + None => obj, + }) +)); + named!(filter>)>, do_parse!( tag_s!("|") >> fname: identifier >> @@ -355,7 +370,7 @@ named!(filter>)>, do_parse!( )); named!(expr_filtered, do_parse!( - obj: expr_attr >> + obj: expr_index >> filters: many0!(filter) >> ({ let mut res = obj; -- cgit