From 34fd0c07de86ff338e261a6454bad88661c07b2e Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Mon, 14 Aug 2017 22:01:53 +0200 Subject: Add support for simple variable definition statements --- askama_derive/src/generator.rs | 15 +++++++++++++++ askama_derive/src/parser.rs | 12 ++++++++++++ 2 files changed, 27 insertions(+) (limited to 'askama_derive/src') diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs index 3c97845..faf4e48 100644 --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -312,6 +312,20 @@ impl<'a> Generator<'a> { self.writeln("))?;"); } + fn write_let(&mut self, ws: &WS, var: &'a Target, val: &Expr) { + self.handle_ws(ws); + self.write("let "); + match *var { + Target::Name(name) => { + self.locals.insert(name); + self.write(name); + }, + } + self.write(" = "); + self.visit_expr(val); + self.writeln(";"); + } + fn write_cond(&mut self, conds: &'a [Cond], ws: &WS) { for (i, &(ref cws, ref cond, ref nodes)) in conds.iter().enumerate() { self.handle_ws(cws); @@ -403,6 +417,7 @@ impl<'a> Generator<'a> { Node::Lit(lws, val, rws) => { self.write_lit(lws, val, rws); } Node::Comment() => {}, Node::Expr(ref ws, ref val) => { self.write_expr(ws, val); }, + Node::Let(ref ws, ref var, ref val) => { self.write_let(ws, var, val); }, Node::Cond(ref conds, ref ws) => { self.write_cond(conds, ws); }, diff --git a/askama_derive/src/parser.rs b/askama_derive/src/parser.rs index b07d8eb..2a6a602 100644 --- a/askama_derive/src/parser.rs +++ b/askama_derive/src/parser.rs @@ -26,6 +26,7 @@ pub enum Node<'a> { Lit(&'a str, &'a str, &'a str), Comment(), Expr(WS, Expr<'a>), + Let(WS, Target<'a>, Expr<'a>), Cond(Vec<(WS, Option>, Vec>)>, WS), Loop(WS, Target<'a>, Expr<'a>, Vec>, WS), Extends(Expr<'a>), @@ -277,6 +278,16 @@ named!(block_if, do_parse!( }) )); +named!(block_let, do_parse!( + pws: opt!(tag_s!("-")) >> + ws!(tag_s!("let")) >> + var: ws!(target_single) >> + ws!(tag_s!("=")) >> + val: ws!(expr_any) >> + nws: opt!(tag_s!("-")) >> + (Node::Let(WS(pws.is_some(), nws.is_some()), var, val)) +)); + named!(block_for, do_parse!( pws1: opt!(tag_s!("-")) >> ws!(tag_s!("for")) >> @@ -331,6 +342,7 @@ named!(block_include, do_parse!( named!(block_node, do_parse!( tag_s!("{%") >> contents: alt!( + block_let | block_if | block_for | block_extends | -- cgit