开发者

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/fi开发者_StackOverflow社区le.html') }}

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


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜