我想包含来自模板的 block 而不是宏,因为许多模板将包含来自许多其他模板的内容,因此 extends
不是一个选项。
我读过很多关于此问题的答案,包括blocks in included files ,但用例似乎总是不同。我怀疑这是不可能完成的。
template1.html
{% block description %}
<p> Here is a description </p>
{% endblock %}
在template2.html
{% from 'template1.html' import description %} <- doesnt work
最佳答案
这里有两个选择。
- 使用宏,这听起来像是您不想做的事情。
- 使用模板过滤器。
假设您使用 Flask,这很简单:
@app.template_filter('get_block')
def template_filter(block, file):
html = render_template(file)
# Then use regex or something to parse
# or even simple splits (better with named blocks), like...
content = html.split('{%% block %s %%}'%(block))[-1]
content = content.split('{%% endblock %%}')[0]
return content
并使用它:
{% 'description'|get_block('template1.html') %}
关于python - 包括 Jinja 模板中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16061051/