Skip to content

Commit

Permalink
Allow macros to be defined and called without arguments
Browse files Browse the repository at this point in the history
This commit introduces a shorthand for defining and calling macros when
using them as a reusable substitute for variables assigned complex values
(e.g. string literals with or without newline escapes). The use-case is
formatting - from my experience it's easier to visually parse a `macro`
`endmacro` block than a multiline variable assignment.

Signed-off-by: mataha <mataha@users.noreply.github.com>
  • Loading branch information
mataha authored and djc committed Jun 12, 2023
1 parent fe5d350 commit cba1fb8
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
7 changes: 5 additions & 2 deletions askama_derive/src/parser/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,13 @@ fn block_call(i: &str) -> IResult<&str, Node<'_>> {
cut(tuple((
opt(tuple((ws(identifier), ws(tag("::"))))),
ws(identifier),
ws(Expr::parse_arguments),
opt(ws(Expr::parse_arguments)),
opt(expr_handle_ws),
))),
));
let (i, (pws, _, (scope, name, args, nws))) = p(i)?;
let scope = scope.map(|(scope, _)| scope);
let args = args.unwrap_or_default();
Ok((i, Node::Call(Ws(pws, nws), scope, name, args)))
}

Expand Down Expand Up @@ -415,7 +416,7 @@ fn block_macro<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Node<'a>> {
ws(keyword("macro")),
cut(tuple((
ws(identifier),
ws(parameters),
opt(ws(parameters)),
opt(expr_handle_ws),
|i| tag_block_end(i, s),
))),
Expand All @@ -435,6 +436,8 @@ fn block_macro<'a>(i: &'a str, s: &State<'_>) -> IResult<&'a str, Node<'a>> {

assert_ne!(name, "super", "invalid macro name 'super'");

let params = params.unwrap_or_default();

Ok((
i,
Node::Macro(
Expand Down
21 changes: 21 additions & 0 deletions testing/templates/macro-no-args.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
1

{%- macro empty -%}
the best thing
{%- endmacro -%}

1

{%- call empty() -%}

1

{%- macro whole() -%}
we've ever done
{%- endmacro -%}

11

{%- call whole -%}

11
10 changes: 10 additions & 0 deletions testing/tests/macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ fn test_macro() {
assert_eq!(t.render().unwrap(), "12foo foo foo34foo foo5");
}

#[derive(Template)]
#[template(path = "macro-no-args.html")]
struct MacroNoArgsTemplate;

#[test]
fn test_macro_no_args() {
let t = MacroNoArgsTemplate;
assert_eq!(t.render().unwrap(), "11the best thing111we've ever done11");
}

#[derive(Template)]
#[template(path = "import.html")]
struct ImportTemplate<'a> {
Expand Down

0 comments on commit cba1fb8

Please sign in to comment.