1

I am making a kind of blog project with Symfony2.

I create the content of my articles with IvoryCKEditorBundle and then display them with {{ article.content|raw }}in Twig.

I want to display on my homepage the first lines of the article: To do this, I need to parse the HTML code and extract strings in it.

How do I extract plain text from HTML, in my Twig template?

Einenlum
  • 600
  • 4
  • 15
  • you can't do it in the template, you have to do it with php –  Jun 28 '14 at 18:01
  • Maybe it is even not the template engine's role… Ok, thanks @Wesabi. I guess I’ll check for this http://stackoverflow.com/questions/1884550/converting-html-to-plain-text-in-php-for-e-mail then. I let the question open to see if there is a way to do it in Twig though. – Einenlum Jun 28 '14 at 18:28

3 Answers3

3

You can get plain text using "striptags" filter then apply "truncate" filter of twig to get portion of your post. for more detail please read my answer https://stackoverflow.com/a/29295738/998686

Community
  • 1
  • 1
Rajesh Meniya
  • 753
  • 1
  • 7
  • 17
2

Twig offers a bunch of filters that you can use. If you want to display only the first line, you can slice your string after a certain number of characters. You should look into the documentation of Twig. There is also another filter to strip the tags if you need to do it before slicing your string.

{{ '12345'|slice(1, 2) }}
{# outputs 23 #}

http://twig.sensiolabs.org/doc/filters/slice.html

Johnny Dew
  • 971
  • 2
  • 13
  • 29
2

If you need extra functionality I guess you need to write new twig extension and put any custom logic there. It do not take much time but allows you to do what you want. Have a look at http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Vazgen Manukyan
  • 1,410
  • 1
  • 12
  • 17