有没有更好的方法在Jinja/Flask中应用nl2br过滤器? [英] Is there a better way to apply a nl2br filter with Jinja/Flask?
问题描述
我正在使用带有Flask的Jinja(已启用自动转义),并且尝试应用此过滤器
I'm using Jinja with Flask (autoescape enabled) and I'm attempting to apply this filter
import re
from jinja2 import evalcontextfilter, Markup, escape
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
app = Flask(__name__)
@app.template_filter()
@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
问题在于它从不应用<br>
,而总是在每行周围应用<p>
.
The problem with it is that it never applies <br>
s and always applies <p>
s around each line.
如果我输入:
1
2
3
4
在textarea
中,它以"u'1 \ r \ n2 \ r \ n \ r \ n3 \ r \ n4'"的形式保存到数据库中,并在使用|nl2br
过滤器放入Jinja时进行过滤出现为
in a textarea
, it gets saved to the DB as "u'1\r\n2\r\n\r\n3\r\n4'" and when put in Jinja with the |nl2br
filter it comes out as
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
我正在寻找它
<p>1<br>2</p>
<p>3<br>4</p>
这种正则表达式方法似乎对我追求的目标来说是过大的.
this regular expression method seems like overkill for what I'm after.
请告诉我,有一种更简单的方法可以完成此操作,因为我整天都在梳理头发,试图找出答案...
Please tell me there is a simpler way to accomplish this as I've been pulling my hair out all day trying to figure it out...
推荐答案
简单,但是稍微复杂些呢?尝试使用此正则表达式:
Simpler no, but how about only slightly more complicated? Try it with this regex:
(?:\r\n|\r(?!\n)|\n){2,}
最初的正则表达式首先将\r\n
作为单行分隔符进行匹配,但是需要匹配其中的两个,因此它将回溯并将其匹配为\r
,然后是\n
.如果下一个字符为\n
,则负前瞻(?!\n)
阻止它单独匹配\r
.
The original regex matches \r\n
as a single line separator at first, but it's required to match two of them, so it backtracks and matches it as \r
followed by \n
. The negative lookahead, (?!\n)
, prevents it from matching \r
alone if the next character is \n
.
这篇关于有没有更好的方法在Jinja/Flask中应用nl2br过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!