mirror of
https://github.com/askama-rs/askama.git
synced 2025-09-30 06:21:13 +00:00
Add parsing and code generation for simple if blocks
This commit is contained in:
parent
9800a5ab64
commit
ce9747c39c
@ -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);
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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()) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user