使用Flask / Jinja2将HTML传递到模板

问题:使用Flask / Jinja2将HTML传递到模板

我正在为Flask和SQLAlchemy构建一个管理员,我想使用来将不同输入的HTML传递给我的视图render_template。模板框架似乎会自动转义html,因此所有<“’>都将转换为html实体。如何禁用它以使HTML正确呈现?

I’m building an admin for Flask and SQLAlchemy, and I want to pass the HTML for the different inputs to my view using render_template. The templating framework seems to escape the html automatically, so all <“‘> are converted to html entities. How can I disable that so that the HTML renders correctly?


回答 0

理想的方法是

{{ something|safe }}

而不是完全关闭自动转义。

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.


回答 1

您还可以从代码中将其声明为HTML安全的:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

然后将该值传递给模板,而他们不必这样做|safe

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don’t have to |safe it.


回答 2

从jinja docs部分HTML Escaping

启用自动转义后,默认情况下所有内容都将转义,除非明确标记为安全的值。可以通过应用程序或使用安全过滤器在模板中对其进行标记。

例:

 <div class="info">
   {{data.email_content|safe}}
 </div>

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

回答 3

当您有很多不需要转义的变量时,可以使用一个autoescape块:

{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

When you have a lot of variables that don’t need escaping, you can use an autoescape block:

{% autoescape off %}
{{ something }}
{{ something_else }}
<b>{{ something_important }}</b>
{% endautoescape %}

回答 4

有些人似乎关闭了自动转义功能,这会带来安全风险可能会影响字符串显示。

如果您只想在字符串中插入一些换行符并将其转换为<br />,则可以使用jinja宏,例如:

{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}

在您的模板中只需使用

{{ linebreaks_for_string( my_string_in_a_variable ) }}

Some people seem to turn autoescape off which carries security risks to manipulate the string display.

If you only want to insert some linebreaks into a string and convert the linebreaks into <br />, then you could take a jinja macro like:

{% macro linebreaks_for_string( the_string ) -%}
{% if the_string %}
{% for line in the_string.split('\n') %}
<br />
{{ line }}
{% endfor %}
{% else %}
{{ the_string }}
{% endif %}
{%- endmacro %}

and in your template just call this with

{{ linebreaks_for_string( my_string_in_a_variable ) }}