0

I save news text in DB as HTML:

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

When i render text like this

{{ post.body | raw }}

everything goes well, but i need to truncate text to 20-30 symbols for preview on main page. So, i tried

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

and then text looks like

<p>Hello, i'm..

How can a hide than html tags? "|raw" filter also does not working while truncation. Please help

Eugene
  • 85
  • 2
  • 5

1 Answers1

6

Conveniently, Twig has a built in function for stripping out HTML tags.

The following would output "Hello, i'm a text ..."

{% set some_html = "<p>Hello, i'm a text!</p><p> More text</p>" %}
{{ some_html[:20]|striptags ~ ' ...' }}
Peter
  • 808
  • 7
  • 15
  • What would be even more convenient is a truncate that preserves the HTML, truncates based on visible words, but closes the current set of tags. [This extension](https://gist.github.com/leon/2857883) may do that (I have not tested). – Chadwick Meyer Feb 20 '15 at 23:16