Skip to content

Instantly share code, notes, and snippets.

@neilmcguigan
Last active May 25, 2023 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilmcguigan/264ef19cc1b1b075965fb7f017c9e7e0 to your computer and use it in GitHub Desktop.
Save neilmcguigan/264ef19cc1b1b075965fb7f017c9e7e0 to your computer and use it in GitHub Desktop.
1. Jinja Macros can return results (but only if `called`):
```
{% macro foo() %}
hello from foo
{{ caller({"bar":1}) if caller is defined }}
{% endmacro %}
{% call(result) foo() %}
{{result.bar}}
{% endcall %}
```
Output is:
hello from foo 1
2. Macros can take varargs and kwargs (but only if you use them in the macro body):
```
{% macro baz() %}
hello from baz {{varargs}} {{kwargs}}
{% endmacro %}
{% set args = [1,2,3] %}
{% set kwargs = {"qux": 1} %}
{{ baz(*args, **kwargs) }}
```
Output is:
hello from baz (1, 2, 3) {'qux': 1}
If you don't want to render them, but still allow them:
```
{% macro baz() %}
{% if false %}{{varargs}} {{kwargs}} {% endif %}
hello from baz
{% endmacro %}
```
Output is:
hello from baz
Or, succinctly:
```
{% macro baz() %}
{{kwargs and varargs if 0}}
hello from baz
{% endmacro %}
```
3. Macros can set variables outside their scope, but only if namespaced:
This won't work:
{% macro zod(x) %} {# with or without passing x #}
{% set x = x + 1%}
{% endmacro %}
{% set x = 1%}
{{zod(x)}}
{{x}}
But this will:
{% macro zed(ns) %} {# with or without passing ns #}
{% set ns.x = ns.x + 1%}
{% endmacro %}
{% set ns = namespace(x=1) %}
{{zed(ns)}}
{{ns.x}}
4. extended Set:
{% set name = "bar" %}
{% set foo | safe %}
<input type="text" name="{{bar}}">
{% endset %}
{{foo}} {# output is <input type="text" name="bar"> #}
5. callbacks:
{% macro foo(save_clicked=none) %} {# where save_clicked can be a macro or python function #}
{% if "save" in request.form %}
{{ save_clicked(...) if save_clicked is callable %}
{% endif %}
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment