【问题标题】:Flask | JINJA 2: render_template_string() with macro imported in context烧瓶 | JINJA 2:在上下文中导入宏的 render_template_string()
【发布时间】:2020-04-21 08:13:03
【问题描述】:

我希望在我的烧瓶博客的文章中提供宏。当我的博客正文发生更改时,我运行以下代码将正文呈现为 HTML:

target.body_html = bleach.linkify(bleach.clean(render_template_string(value),tags=allowed_tags, attributes=allowed_attr, strip=True))

render_template_string(value) 是我关心的部分。要在模板字符串(值)中使用宏,每个字符串都必须包含以下内容,以便我在文章正文中使用此文件中的宏:

{% import "includes/macros.html.j2" as macros %}

确保作者可以访问我在他们所有文章中编写的宏是不合理的。有没有办法通过 render_template_string() 函数传递该参数,以便不必在每个字符串中定义它?或者以其他方式创建一个在其中呈现字符串的模板?类似于以下内容:

render_template_string(string,macros=function_to_import_macros("includes/macros.html.j2")) 

【问题讨论】:

    标签: python-3.x flask jinja2


    【解决方案1】:

    虽然似乎没有将整个宏模板作为上下文传递的解决方案,但 get_template_attribute 似乎允许您一次传递一个宏。示例:

    包括/macros.html.j2:

    {% macro hello() %}Hello!{% endmacro %}
    {% macro hello_with_name(name) %}Hello, {{ name }}!{% endmacro %}
    

    模板渲染代码:

    hello = get_template_attribute("includes/macros.html.j2","hello")
    hello_with_name = get_template_attribute("includes/macros.html.j2","hello_with_name")
    return render_template("index.html", hello=hello,hello_with_name=hello_with_name)
    

    index.html:

    {{ hello() }}
    {{ hello_with_name("Bob") }}
    

    此解决方案将允许在渲染模板或模板字符串时将单个宏添加到上下文中,甚至可以通过此方法将其添加到全局上下文中。如果有人知道如何添加一个充满宏的整个模板,那就太棒了,但这允许基本所需的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-21
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 2021-03-27
      • 2013-06-17
      • 1970-01-01
      相关资源
      最近更新 更多