2012-05-03 117 views
9

在我的網絡應用中,用戶可以發表博文。當我顯示博文時,不會顯示換行符,因爲我沒有用<br>標籤取代新行。問題是我已經在Jinja中自動轉義了,所以<br>標籤被轉義了。我不想暫時禁用autoescaping,我想專門允許<br>標籤。我將如何做到這一點?允許使用Google App Engine和Jinja2的<br>標籤

+0

如果您想要遵守換行符,您可以使用'textarea'。 – bossylobster

回答

26

我有另一個答案,我認爲是最好的。最初,我只是按原樣顯示我的變量post.content,並且換行符未被保留。這裏沒有任何解決方案能夠工作(良好),我的預解決方案只是一個快速解決方案,並且存在重大問題。這纔是真正的解決方案:

{% for line in post.content.splitlines() %} 
    {{line}}<br> 
{% endfor %} 
+1

偉大的解決方案! – billwild

+0

謝謝你的工作! –

-1

解決的辦法是在我有內容的區域放置<pre></pre>標籤。

+2

這不是一個好的解決方案 - pre對其他事情有影響,比如換行。 –

-1

最簡單的方法是自己逃離現場,然後添加換行符。當你在忍者傳入時,將其標記爲安全的,這樣它就不會自動轉義。

2

可以使用|safe過濾器,或使用autoescape塊:

{% autoescape false %} 
{{ content goes here }} 
{% autoescape %} 

您還可以設置在environment autoescaping到False

+2

但是,如果它不安全呢? – LtWorf

+0

@LWWorf是對的。您應該假定用戶輸入的內容是惡意的。大部分不會,但是你不希望那個插入JavaScript的邪惡人物給你的用戶帶來病毒。 -1 – jpmc26

2

在你的模型對象,增加一個功能是這樣的:

class Post(db.Model): 
    # ... 

    def html_content(self): 
     # Escape, then convert newlines to br tags, then wrap with Markup object 
     # so that the <br> tags don't get escaped. 
     def escape(s): 
      # unicode() forces the conversion to happen immediately, 
      # instead of at substitution time (else <br> would get escaped too) 
      return unicode(jinja2.escape(s)) 
     return jinja2.Markup(escape(self.content).replace('\n', '<br>')) 

然後在你的模板,只需調用:

<p>{{ post.html_content() }}</p> 
0

您可以創建一個Jinja2的過濾器:

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 

您需要將過濾器添加到您的Jinja2環境之前,你可以使用它:

JINJA2_ENV.filters['nl2br'] = jinja2_filters.nl2br 

在您的模板中,您可以使用該過濾器:

{{post.content|nl2br}} 
0

這裏有一個過濾器寫我自己:

import jinja2 

@jinja2.evalcontextfilter 
def nl2br(eval_ctx, value): 
    result = jinja2.escape(value).unescape().replace('\n', '<br>') 
    if eval_ctx.autoescape: 
     result = jinja2.Markup(result) 
    return result 

,並通過調用過濾器添加到jinja2.Environment()

jinja_env.filters['nl2br'] = nl2br 
+0

請注意,這是不安全的,因爲它傳遞HTML內容。應該是:result = escape(value).replace(「\ n」,Markup(「
」)) – gpothier

0

請注意,我都默認autoescape上,所以我不簽入這個功能,但是這是我使用的是什麼

def nl2br(value): 
    split = value.split('\n') 
    return jinja2.Markup('<br>').join(split) 

那當然,

jinja_env.filters['nl2br'] = nl2br