如何在Jinja2的视图(或模板)中将字符串标记为“安全”?

时间:2022-03-20 20:46:10

Typically when you want to mark string output as safe in Jinja2 you do something like this:

通常,当您想在Jinja2中将字符串输出标记为安全时,您可以执行以下操作:

{{ output_string|safe() }}

However, what if output_string is always safe? I don't want to repeat myself every time by using the safe filter.

但是,如果output_string总是安全的呢?我不想每次都使用安全过滤器重复自己。

I have a custom filter called "emailize" that preps urls for output in an email. The ampersands always seem to become escaped. Is there a way in my custom filter to mark the output as safe?

我有一个名为“emailize”的自定义过滤器,它会在电子邮件中为输出添加网址。 &符似乎总是逃脱。我的自定义过滤器中有一种方法可以将输出标记为安全吗?

2 个解决方案

#1


11  

Use the Markup class:

使用Markup类:

class jinja2.Markup([string])

class jinja2.Markup([string])

Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped.

将字符串标记为可安全包含在HTML / XML输出中而无需转义。

#2


11  

Check SafeString, like for example:

检查SafeString,例如:

from django.utils.safestring import SafeString
...
return context.update({
        'html_string': SafeString(html_string),
})

#1


11  

Use the Markup class:

使用Markup类:

class jinja2.Markup([string])

class jinja2.Markup([string])

Marks a string as being safe for inclusion in HTML/XML output without needing to be escaped.

将字符串标记为可安全包含在HTML / XML输出中而无需转义。

#2


11  

Check SafeString, like for example:

检查SafeString,例如:

from django.utils.safestring import SafeString
...
return context.update({
        'html_string': SafeString(html_string),
})