python - 包括 Jinja 模板中的 block

标签 python jinja2

我想包含来自模板的 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

最佳答案

这里有两个选择。

  1. 使用宏,这听起来像是您不想做的事情。
  2. 使用模板过滤器。

假设您使用 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/

相关文章:

Python Flask 从像 render_template 这样的变量渲染文本

python - 使用混合属性来计算 previous sibling 姐妹

javascript - 正则表达式 - 如果在大括号内则不匹配

templates - 在 Jinja 中动态获取变量(从字符串)

python - Jinja2 宏导入 "with context"和全局变量 : {% from file. html import macro_name with context %}

python - 如何在 html 表中编辑从数据库中获取的数据? flask ,Jinja2

python 'module' 对象没有属性 'compile'

python - 在 Pandas 数据框中插入列

python - Redis PUB/SUB 可以支持多少个 channel ?

python - 无法在从 python 模块创建的 pip 包中使用 jinja2 模板