Python 3.x Flask | JINJA 2:在上下文中导入宏时呈现_模板_字符串()

Python 3.x Flask | JINJA 2:在上下文中导入宏时呈现_模板_字符串(),python-3.x,flask,jinja2,Python 3.x,Flask,Jinja2,我希望在我的flask博客的文章中提供宏。当我的博客主体发生更改时,我会运行以下代码将主体呈现为HTML: target.body_html = bleach.linkify(bleach.clean(render_template_string(value),tags=allowed_tags, attributes=allowed_attr, strip=True)) 渲染模板字符串(值)是我关心的部分。要在模板字符串(值)中使用宏,每个字符串必须包含以下内容,以便我在文章正文中使用此文件

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

target.body_html = bleach.linkify(bleach.clean(render_template_string(value),tags=allowed_tags, attributes=allowed_attr, strip=True))
渲染模板字符串(值)是我关心的部分。要在模板字符串(值)中使用宏,每个字符串必须包含以下内容,以便我在文章正文中使用此文件中的宏:

{% import "includes/macros.html.j2" as macros %}
这对于确保作者能够访问我在他们所有文章中编写的宏是不合理的。有没有办法通过render_template_string()函数传递该参数,从而不必在每个字符串中定义它?或者创建一个在其中呈现字符串的模板?如下所示:

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

虽然似乎没有将整个宏模板作为上下文传递的解决方案,但“获取模板”属性似乎允许您一次传递一个宏。例如:

包括/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") }}
此解决方案允许在呈现模板或模板字符串时将单个宏添加到上下文中,甚至可以通过此方法添加到全局上下文中。如果有人知道如何添加一个完整的宏模板,那就太棒了,但这允许基本的功能