From 76bd8054f465065ce6e870c433484043276fb647 Mon Sep 17 00:00:00 2001 From: Bastien Orivel Date: Fri, 29 Apr 2022 13:12:18 +0200 Subject: [PATCH] Allow `{% endmacro name %}` Just migrated a repo from tera to askama and this was one of the only things that was different. This is also coherent with `{% block %}` for which I added the same feature years ago. --- askama_shared/src/parser.rs | 24 +++++++++++++----------- testing/templates/macro.html | 12 ++++++++++++ testing/tests/macro.rs | 2 +- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/askama_shared/src/parser.rs b/askama_shared/src/parser.rs index 624fbc637..19df79551 100644 --- a/askama_shared/src/parser.rs +++ b/askama_shared/src/parser.rs @@ -996,7 +996,7 @@ fn block_import(i: &str) -> IResult<&str, Node<'_>> { } fn block_macro<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Node<'a>> { - let mut p = tuple(( + let mut start = tuple(( opt(expr_handle_ws), ws(tag("macro")), cut(tuple(( @@ -1004,19 +1004,21 @@ fn block_macro<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Node<'a>> { ws(parameters), opt(expr_handle_ws), |i| tag_block_end(i, s), - cut(tuple(( - |i| parse_template(i, s), - cut(tuple(( - |i| tag_block_start(i, s), - opt(expr_handle_ws), - ws(tag("endmacro")), - opt(expr_handle_ws), - ))), - ))), ))), )); + let (i, (pws1, _, (name, params, nws1, _))) = start(i)?; + + let mut end = cut(tuple(( + |i| parse_template(i, s), + cut(tuple(( + |i| tag_block_start(i, s), + opt(expr_handle_ws), + ws(tag("endmacro")), + cut(tuple((opt(ws(tag(name))), opt(expr_handle_ws)))), + ))), + ))); + let (i, (contents, (_, pws2, _, (_, nws2)))) = end(i)?; - let (i, (pws1, _, (name, params, nws1, _, (contents, (_, pws2, _, nws2))))) = p(i)?; assert_ne!(name, "super", "invalid macro name 'super'"); Ok(( diff --git a/testing/templates/macro.html b/testing/templates/macro.html index 30ea742e7..f2f89e0f0 100644 --- a/testing/templates/macro.html +++ b/testing/templates/macro.html @@ -11,3 +11,15 @@ {%- call thrice(s) -%} 3 + +{%- macro twice(param) -%} + +{{ param }} {{ param }} + +{%- endmacro twice -%} + +4 + +{%- call twice(s) -%} + +5 diff --git a/testing/tests/macro.rs b/testing/tests/macro.rs index e449dd57b..6b0eca5d0 100644 --- a/testing/tests/macro.rs +++ b/testing/tests/macro.rs @@ -9,7 +9,7 @@ struct MacroTemplate<'a> { #[test] fn test_macro() { let t = MacroTemplate { s: "foo" }; - assert_eq!(t.render().unwrap(), "12foo foo foo3"); + assert_eq!(t.render().unwrap(), "12foo foo foo34foo foo5"); } #[derive(Template)]