0

我希望在我的烧瓶博客的文章中提供宏。当我的博客正文发生更改时,我运行以下代码将正文呈现为 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")) 
4

1 回答 1

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)

索引.html:

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

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

于 2020-04-22T11:03:54.613 回答