Skip to content

Commit

Permalink
Add support for Index operation (see #95)
Browse files Browse the repository at this point in the history
  • Loading branch information
djc committed Jun 23, 2018
1 parent 381997a commit f1422f5
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
9 changes: 9 additions & 0 deletions askama_derive/src/generator.rs
Expand Up @@ -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),
Expand Down Expand Up @@ -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,
Expand Down
17 changes: 16 additions & 1 deletion askama_derive/src/parser.rs
Expand Up @@ -12,6 +12,7 @@ pub enum Expr<'a> {
Path(Vec<&'a str>),
Array(Vec<Expr<'a>>),
Attr(Box<Expr<'a>>, &'a str),
Index(Box<Expr<'a>>, Box<Expr<'a>>),
Filter(&'a str, Vec<Expr<'a>>),
Unary(&'a str, Box<Expr<'a>>),
BinOp(&'a str, Box<Expr<'a>>, Box<Expr<'a>>),
Expand Down Expand Up @@ -347,6 +348,20 @@ named!(expr_attr<Input, Expr>, do_parse!(
})
));

named!(expr_index<Input, Expr>, 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<Input, (&str, Option<Vec<Expr>>)>, do_parse!(
tag_s!("|") >>
fname: identifier >>
Expand All @@ -355,7 +370,7 @@ named!(filter<Input, (&str, Option<Vec<Expr>>)>, do_parse!(
));

named!(expr_filtered<Input, Expr>, do_parse!(
obj: expr_attr >>
obj: expr_index >>
filters: many0!(filter) >>
({
let mut res = obj;
Expand Down

0 comments on commit f1422f5

Please sign in to comment.