Romeo M.
Romeo M.

Reputation: 3278

jinja2 load template file from template

Is there a way I can load a jinja2 template from within another template file? Something like

{{ render_template('path/to/file.html') }}

I have some snippets which I want to reuse, so it's important for me to have this functionality.

Upvotes: 45

Views: 44608

Answers (3)

okovko
okovko

Reputation: 1911

You should make template files with {% macro -%}s and use {% import "file" as file %} to use the macros in other template files. See the docs.

Here is an example:

<!- in common_macros.html ->
{% macro common_idiom1(var1, var2, ... varN) -%}
    <!- your idiom, where you can use var1 through varN ->
{%- endmacro %}
<!- in my_template.html ->
{% import "common_macros.html" as idioms %}
{{ idioms.common_idiom1(a, b, ... N) }}

Specifically this answer allows the OP to pass arguments to his macros, similar to the behavior he desired like how render_template behaves (simply including the file as previous answers have stated above does not achieve the same behavior as render_template).

This is generally better than making a fresh template for every idiom, or than using inheritance, which is a special case solution (what if you want to use the snippet multiple times in one template)?

Upvotes: 13

Ulrich Dangel
Ulrich Dangel

Reputation: 4625

{% include "file" %} does this. See the jinja2 docs for more information.

Upvotes: 58

Wooble
Wooble

Reputation: 90037

Use either the extends tag or the include tag, depending on how you want to design your multi-file views.

Upvotes: 13

Related Questions