From ce9747c39c7523fbefe3700fbba93a6ac0c5341a Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Sat, 7 Jan 2017 21:02:48 +0100 Subject: Add parsing and code generation for simple if blocks --- askama/src/generator.rs | 13 +++++++++++++ askama/src/parser.rs | 17 ++++++++++++++++- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/askama/src/generator.rs b/askama/src/generator.rs index 0e80265..adfa278 100644 --- a/askama/src/generator.rs +++ b/askama/src/generator.rs @@ -79,11 +79,24 @@ impl Generator { self.writeln(")).unwrap();"); } + fn write_cond(&mut self, cond: &Expr, nodes: &Vec) { + self.write("if "); + self.visit_expr(cond); + self.writeln(" {"); + self.indent(); + self.handle(nodes); + self.dedent(); + self.writeln("}"); + } + fn handle(&mut self, tokens: &Vec) { for n in tokens { match n { &Node::Lit(val) => { self.write_lit(val); }, &Node::Expr(ref val) => { self.write_expr(&val); }, + &Node::Cond(ref cond, ref nodes) => { + self.write_cond(&cond, &nodes); + }, } } } diff --git a/askama/src/parser.rs b/askama/src/parser.rs index cd93971..38d84d4 100644 --- a/askama/src/parser.rs +++ b/askama/src/parser.rs @@ -9,6 +9,7 @@ pub enum Expr<'a> { pub enum Node<'a> { Lit(&'a [u8]), Expr(Expr<'a>), + Cond(Expr<'a>, Vec>), } fn take_content(i: &[u8]) -> IResult<&[u8], Node> { @@ -58,7 +59,21 @@ named!(expr_node, map!( delimited!(tag_s!("{{"), ws!(expr_filtered), tag_s!("}}")), Node::Expr)); -named!(parse_template< Vec >, many1!(alt!(take_content | expr_node))); +named!(block_if, do_parse!( + tag_s!("{%") >> + ws!(tag_s!("if")) >> + cond: ws!(expr_filtered) >> + ws!(tag_s!("%}")) >> + block: parse_template >> + ws!(tag_s!("{%")) >> + ws!(tag_s!("endif")) >> + tag_s!("%}") >> + (Node::Cond(cond, block)))); + +named!(parse_template< Vec >, many1!(alt!( + take_content | + expr_node | + block_if))); pub fn parse<'a>(src: &'a str) -> Vec { match parse_template(src.as_bytes()) { -- cgit