Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 load template file from template

Tags:

jinja2

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.

like image 672
Romeo M. Avatar asked Sep 07 '11 17:09

Romeo M.


3 Answers

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

like image 191
Ulrich Dangel Avatar answered Oct 06 '22 16:10

Ulrich Dangel


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)?

like image 32
okovko Avatar answered Oct 06 '22 18:10

okovko


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

like image 26
Wooble Avatar answered Oct 06 '22 17:10

Wooble