简体   繁体   English

如何正确应用django / jinja2模板过滤器'escape'和'linebreaks'?

[英]How to apply django/jinja2 template filters 'escape' and 'linebreaks' correctly?

I'm currently trying to escape a variable using django templating filters as below. 我正在尝试使用django模板过滤器来逃避变量,如下所示。 I use a jinja2 template engine instead of just django's primary templateing engine 我使用jinja2模板引擎而不仅仅是django的主要模板引擎

{{ my_variable|escape|linebreaks }}

the output of a string with newlines is as follows: 带换行符的字符串输出如下:

Lorem ipsum <br /> dolor sit amet <br />rg srg
gs rgsr rsg serg<br />r srg

Ideally the 理想情况下

<br />

is not supposed to be escaped, as it is added by the "linebreaks" filter. 不应该被转义,因为它是由“linebreaks”过滤器添加的。 There are no html tags with the original string. 原始字符串没有html标签。

I've tried: 我试过了:

{{ my_variable|linebreaks|escape }}

But, it turns out even worse: 但是,结果更糟:

<p>Lorem ipsum <br /> dolor sit amet <br />rg srg</p>
<p>gs rgsr rsg serg<br />r srg</p>

Does anyone knows whether I did something wrong with applying the template filter, and/or able to point me in the right direction? 有谁知道我是否在应用模板过滤器时出错了,并且/或者能够指出我正确的方向?

Thanks. 谢谢。

So you are using django's linebreaks filter in a jinja2 template? 所以你在jinja2模板中使用django的linebreaks过滤器? In that case, I would assume that the way django marks a string safe may not be compatible with jinja2, therefore escaping the tags added by django (if autoescape is active). 在这种情况下,我会假设django标记字符串安全的方式可能与jinja2不兼容,因此转义django添加的标记(如果autoescape处于活动状态)。

What if you added the safe filter from jinja2 to the end? 如果你从jinja2添加安全过滤器到底怎么办?

{{ my_variable|escape|linebreaks|safe }}

Otherwise, there is an example for a custom filter in jinja2 documentation that seems to be similar to django's linebreaks. 否则,jinja2文档中的自定义过滤器有一个示例,似乎与django的换行符类似。 http://jinja.pocoo.org/docs/api/#custom-filters http://jinja.pocoo.org/docs/api/#custom-filters

import re
from jinja2 import evalcontextfilter, Markup, escape

_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')

@evalcontextfilter
def nl2br(eval_ctx, value):
    result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', '<br>\n')
                      for p in _paragraph_re.split(escape(value)))
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

Silly me, it seems that I can use: 傻我,似乎我可以使用:

{{ my_variable|forceescape|linebreaks }}

to force the 'escape' filter to apply first. 强制首先应用'escape'过滤器。 By default 'escape' only apply at end of all other filters despite of position, so force_escape is the other most simple alternative. 默认情况下,'escape'仅应用于所有其他过滤器的末尾,尽管有位置,因此force_escape是另一个最简单的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM