【发布时间】:2017-10-30 01:29:29
【问题描述】:
我想import 一个 Jinja 模板,它也有顶级内容,但不执行内容本身。例如:
template_with_macros.html:
{% macro link(text, url) %}
<a href='{{ url }}'>{{ text }}</a>
{% endmacro %}
{% for text, url in {'Google': 'http://google.com', 'Stack Overflow': 'http://stackoverflow.com'}.items() %}
{{ link(text, url) }}
{% endfor %}
template_that_uses_macros.html:
{% import "template_with_macros.html" as macros %}
{{ macros.link("Homepage", "/") }}
当您import 一个 Jinja 模板时,该模板的内容不包括在内,但仍会执行,这意味着任何不存在的变量都会导致错误,以及执行不需要的代码时发生的其他不良情况。
有没有办法在不执行其内容的情况下导入 Jinja 模板?
我想这样做,而不是将宏完全分解到另一个文件中,因为这将是在我的应用程序中组织模板代码的一种更整洁的方式。
【问题讨论】: