2014-02-19 81 views
0

我在DB新聞保存文本爲HTML:嫩枝不正確截斷HTML

<p>Hello, i'm a text!</p><p> More text</p> 

當我渲染這樣

{{ post.body | raw }} 

一切文本順利,但我需要截斷文本20-30在主頁上預覽的符號。 所以,我試圖

{{ p.body[:20] ~ '..' }} 

,然後文本看起來像

<p>Hello, i'm.. 

如何能躲比html標籤? 「| raw」過濾器在截斷時也不起作用。 請幫忙

回答

6

方便地,Twig具有內置的HTML標籤剝離功能。

下將輸出「你好,我是一個文本......」

{% set some_html = "<p>Hello, i'm a text!</p><p> More text</p>" %} 
{{ some_html[:20]|striptags ~ ' ...' }} 
+0

謝謝!現在看起來不錯:) – Eugene

+0

什麼會更方便的是截斷,保留的HTML,截斷基於可見的單詞,但關閉當前的一組標籤。 [此擴展](https://gist.github.com/leon/2857883)可能會這樣做(我還沒有測試過)。 –