From 726ca1cc3356f7aa59d7c2730c9f3b3588236cb0 Mon Sep 17 00:00:00 2001 From: René Kijewski Date: Fri, 30 Jul 2021 17:04:30 +0200 Subject: Add {% break %} and {% continue %} This PR adds `{% break %}` and `{% continue %}` statements to break out of a loop, or continue with the next element of the iterator. --- askama_shared/src/generator.rs | 10 ++++++++++ askama_shared/src/parser.rs | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) (limited to 'askama_shared/src') diff --git a/askama_shared/src/generator.rs b/askama_shared/src/generator.rs index ec468e5..3bcb5d9 100644 --- a/askama_shared/src/generator.rs +++ b/askama_shared/src/generator.rs @@ -459,6 +459,16 @@ impl<'a, S: std::hash::BuildHasher> Generator<'a, S> { // No whitespace handling: child template top-level is not used, // except for the blocks defined in it. } + Node::Break(ws) => { + self.handle_ws(ws); + self.write_buf_writable(buf)?; + buf.writeln("break;")?; + } + Node::Continue(ws) => { + self.handle_ws(ws); + self.write_buf_writable(buf)?; + buf.writeln("continue;")?; + } } } diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs index 66f2ec1..910c942 100644 --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -27,6 +27,8 @@ pub enum Node<'a> { Import(Ws, &'a str, &'a str), Macro(&'a str, Macro<'a>), Raw(Ws, &'a str, Ws), + Break(Ws), + Continue(Ws), } #[derive(Debug, PartialEq)] @@ -1068,6 +1070,18 @@ fn block_raw<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a>> )) } +fn break_statement(i: &[u8]) -> IResult<&[u8], Node<'_>> { + let mut p = tuple((opt(tag("-")), ws(tag("break")), opt(tag("-")))); + let (i, (pws, _, nws)) = p(i)?; + Ok((i, Node::Break(Ws(pws.is_some(), nws.is_some())))) +} + +fn continue_statement(i: &[u8]) -> IResult<&[u8], Node<'_>> { + let mut p = tuple((opt(tag("-")), ws(tag("continue")), opt(tag("-")))); + let (i, (pws, _, nws)) = p(i)?; + Ok((i, Node::Continue(Ws(pws.is_some(), nws.is_some())))) +} + fn block_node<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a>> { let mut p = tuple(( |i| tag_block_start(i, s), @@ -1083,6 +1097,8 @@ fn block_node<'a>(i: &'a [u8], s: &'a Syntax<'a>) -> IResult<&'a [u8], Node<'a>> |i| block_block(i, s), |i| block_macro(i, s), |i| block_raw(i, s), + break_statement, + continue_statement, )), cut(|i| tag_block_end(i, s)), )); -- cgit