diff options
author | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2017-01-07 21:02:48 +0100 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2017-01-07 21:02:48 +0100 |
commit | ce9747c39c7523fbefe3700fbba93a6ac0c5341a (patch) | |
tree | 3625d1ee405efb4d14a5f0898b1c0dc4374f2cd8 | |
parent | 9800a5ab6499a7d3488fc4db49d92b5f156b3940 (diff) | |
download | askama-ce9747c39c7523fbefe3700fbba93a6ac0c5341a.tar.gz askama-ce9747c39c7523fbefe3700fbba93a6ac0c5341a.tar.bz2 askama-ce9747c39c7523fbefe3700fbba93a6ac0c5341a.zip |
Add parsing and code generation for simple if blocks
Diffstat (limited to '')
-rw-r--r-- | askama/src/generator.rs | 13 | ||||
-rw-r--r-- | askama/src/parser.rs | 17 |
2 files changed, 29 insertions, 1 deletions
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<Node>) { + self.write("if "); + self.visit_expr(cond); + self.writeln(" {"); + self.indent(); + self.handle(nodes); + self.dedent(); + self.writeln("}"); + } + fn handle(&mut self, tokens: &Vec<Node>) { 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<Node<'a>>), } fn take_content(i: &[u8]) -> IResult<&[u8], Node> { @@ -58,7 +59,21 @@ named!(expr_node<Node>, map!( delimited!(tag_s!("{{"), ws!(expr_filtered), tag_s!("}}")), Node::Expr)); -named!(parse_template< Vec<Node> >, many1!(alt!(take_content | expr_node))); +named!(block_if<Node>, 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<Node> >, many1!(alt!( + take_content | + expr_node | + block_if))); pub fn parse<'a>(src: &'a str) -> Vec<Node> { match parse_template(src.as_bytes()) { |