Skip to content

Commit

Permalink
Add documentation for macro named arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
GuillaumeGomez committed Nov 20, 2023
1 parent 3598ae4 commit c4334fb
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
52 changes: 52 additions & 0 deletions book/src/template_syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -587,3 +587,55 @@ You can optionally specify the name of the macro in `endmacro`:
```html
{% macro heading(arg) %}<p>{{arg}}</p>{% endmacro heading %}
```

You can also specify arguments by their name (as defined in the macro):

```
{% macro heading(arg, bold) %}
<h1>{{arg}} <b>{{bold}}</b></h1>
{% endmacro %}
{% call heading(bold="something", arg="title") %}
```

You can use whitespace characters around `=`:

```
{% call heading(bold = "something", arg = "title") %}
```

You can mix named and non-named arguments when calling a macro:

```
{% call heading(bold="something", "title") %}
```

In this case, the named arguments will be passed to the related parameter and then the other
arguments will be placed in what remains. Let's explain it in code:

```
{% macro heading(arg1, arg2, arg3, arg4) %}
{% endmacro %}
{% call heading("something", arg2="title", arg4="ah", "b") %}
```

First it'll be replaced like this:

```
arg1 =
arg2 = "title"
arg3 =
arg4 = "ah"
```

Then `arg1` and `arg3` will be filled in the order of the arguments given to the macro call:

```
arg1 = "something"
arg2 = "title"
arg3 = "b"
arg4 = "ah"
```
9 changes: 9 additions & 0 deletions testing/tests/ui/macro_named_argument.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,14 @@ struct InvalidNamedArg;
{%- call thrice(param1=2, param1=3) -%}", ext = "html")]
struct InvalidNamedArg2;

// Ensures that filters can't have named arguments.
#[derive(Template)]
#[template(source = "{%- macro thrice(param1, param2) -%}
{{ param1 }} {{ param2 }}
{%- endmacro -%}
{%- call thrice(param1=2, 3) | filter(param1=12) -%}", ext = "html")]
struct InvalidNamedArg3;

fn main() {
}
9 changes: 9 additions & 0 deletions testing/tests/ui/macro_named_argument.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ error: named argument `param1` was passed more than once
| ^^^^^^^^
|
= note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info)

error: problems parsing template source at row 5, column 29 near:
"| filter(param1=12) -%}"
--> tests/ui/macro_named_argument.rs:20:10
|
20 | #[derive(Template)]
| ^^^^^^^^
|
= note: this error originates in the derive macro `Template` (in Nightly builds, run with -Z macro-backtrace for more info)

0 comments on commit c4334fb

Please sign in to comment.