【问题标题】:Including Blocks from Jinja templates包括来自 Jinja 模板的块
【发布时间】:2013-04-17 13:14:41
【问题描述】:

我想包含来自模板的块而不是宏,因为许多模板将包含来自许多其他模板的内容,所以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

【问题讨论】:

    标签: python jinja2


    【解决方案1】:

    这里有两个选择。

    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') %}
    

    【讨论】:

    • 我希望只用 Jinja 就能做到这一点,但感谢您的聪明建议。
    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多