From 4af73a868c7d35641f8a1bcd0a82f8c7db411d8d Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Fri, 20 Oct 2017 10:09:50 +0200 Subject: Add support for array literals (fixes #59) --- askama_shared/src/generator.rs | 13 +++++++++++++ askama_shared/src/parser.rs | 18 ++++++++++++++++++ testing/tests/simple.rs | 11 +++++++++++ 3 files changed, 42 insertions(+) diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs index f58d1dd..dcdea32 100644 --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -573,6 +573,7 @@ impl<'a> Generator<'a> { Expr::StrLit(s) => self.visit_str_lit(s), Expr::Var(s) => self.visit_var(s), Expr::Path(ref path) => self.visit_path(path), + Expr::Array(ref elements) => self.visit_array(elements), Expr::Attr(ref obj, name) => self.visit_attr(obj, name), Expr::Filter(name, ref args) => self.visit_filter(name, args), Expr::BinOp(op, ref left, ref right) => @@ -683,6 +684,18 @@ impl<'a> Generator<'a> { DisplayWrap::Unwrapped } + fn visit_array(&mut self, elements: &Vec) -> DisplayWrap { + self.write("["); + for (i, el) in elements.iter().enumerate() { + if i > 0 { + self.write(", "); + } + self.visit_expr(el); + } + self.write("]"); + DisplayWrap::Unwrapped + } + fn visit_path(&mut self, path: &Vec<&str>) -> DisplayWrap { for (i, part) in path.iter().enumerate() { if i > 0 { diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs index 7cd8936..accefd2 100644 --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -7,6 +7,7 @@ pub enum Expr<'a> { StrLit(&'a str), Var(&'a str), Path(Vec<&'a str>), + Array(Vec>), Attr(Box>, &'a str), Filter(&'a str, Vec>), BinOp(&'a str, Box>, Box>), @@ -128,6 +129,22 @@ named!(expr_num_lit, map!(num_lit, |s| Expr::NumLit(s) )); +named!(expr_array_lit, do_parse!( + ws!(tag_s!("[")) >> + first: expr_any >> + rest: many0!(do_parse!( + ws!(tag_s!(",")) >> + part: expr_any >> + (part) + )) >> + ws!(tag_s!("]")) >> + ({ + let mut elements = vec![first]; + elements.extend(rest); + Expr::Array(elements) + }) +)); + named!(expr_str_lit, map!( delimited!(char!('"'), is_not!("\""), char!('"')), |s| Expr::StrLit(str::from_utf8(s).unwrap()) @@ -204,6 +221,7 @@ named!(expr_single, alt!( expr_num_lit | expr_str_lit | expr_path | + expr_array_lit | expr_var | expr_group )); diff --git a/testing/tests/simple.rs b/testing/tests/simple.rs index fd30499..bee5690 100644 --- a/testing/tests/simple.rs +++ b/testing/tests/simple.rs @@ -184,3 +184,14 @@ fn test_path_compare() { let t = PathCompareTemplate { x: Alphabet::Alpha }; assert_eq!(t.render().unwrap(), "true"); } + + +#[derive(Template)] +#[template(source = "{% for i in [1, 2] %}{{ i }}{% endfor %}", ext = "txt")] +struct ArrayTemplate {} + +#[test] +fn test_slice_literal() { + let t = ArrayTemplate {}; + assert_eq!(t.render().unwrap(), "12"); +} -- cgit