Skip to content
This repository was archived by the owner on Mar 11, 2025. It is now read-only.

Commit 21f840a

Browse files
GuillaumeGomezdjc
authored andcommitted
Add documentation for macro named arguments
1 parent 28e2675 commit 21f840a

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

book/src/template_syntax.md

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -564,7 +564,7 @@ You can define macros within your template by using `{% macro name(args) %}`, en
564564

565565
You can then call it with `{% call name(args) %}`:
566566

567-
```
567+
```jinja
568568
{% macro heading(arg) %}
569569
570570
<h1>{{arg}}</h1>
@@ -576,14 +576,59 @@ You can then call it with `{% call name(args) %}`:
576576

577577
You can place macros in a separate file and use them in your templates by using `{% import %}`:
578578

579-
```
579+
```jinja
580580
{%- import "macro.html" as scope -%}
581581
582582
{% call scope::heading(s) %}
583583
```
584584

585585
You can optionally specify the name of the macro in `endmacro`:
586586

587-
```html
587+
```jinja
588588
{% macro heading(arg) %}<p>{{arg}}</p>{% endmacro heading %}
589589
```
590+
591+
You can also specify arguments by their name (as defined in the macro):
592+
593+
```jinja
594+
{% macro heading(arg, bold) %}
595+
596+
<h1>{{arg}} <b>{{bold}}</b></h1>
597+
598+
{% endmacro %}
599+
600+
{% call heading(bold="something", arg="title") %}
601+
```
602+
603+
You can use whitespace characters around `=`:
604+
605+
```jinja
606+
{% call heading(bold = "something", arg = "title") %}
607+
```
608+
609+
You can mix named and non-named arguments when calling a macro:
610+
611+
```
612+
{% call heading("title", bold="something") %}
613+
```
614+
615+
However please note than named arguments must always come **last**.
616+
617+
Another thing to note, if a named argument is referring to an argument that would
618+
be used for a non-named argument, it will error:
619+
620+
```jinja
621+
{% macro heading(arg1, arg2, arg3, arg4) %}
622+
{% endmacro %}
623+
624+
{% call heading("something", "b", arg4="ah", arg2="title") %}
625+
```
626+
627+
In here it's invalid because `arg2` is the second argument and would be used by
628+
`"b"`. So either you replace `"b"` with `arg3="b"` or you pass `"title"` before:
629+
630+
```jinja
631+
{% call heading("something", arg3="b", arg4="ah", arg2="title") %}
632+
{# Equivalent of: #}
633+
{% call heading("something", "title", "b", arg4="ah") %}
634+
```

0 commit comments

Comments
 (0)