Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 twig - raw & slice filter together doesn't work

In my twig template I have the following code:

<td>{{ object.content|length > 50 ? object.content|raw|slice(0, 50) ~ '...' : object.content|raw  }}</td>

My object object.content is a string like this:

<p>Nullam quis risus eget urna mollis ornare vel eu leo. Donec ullamcorper nulla non metus auctor fringilla.</p>

I would like to output the string without the <p>, <b>, .. tags. That's why I add the |raw filter. I also only want to output 50 characters of the whole string.

The slicing of 50 characters works but he still shows the <p>, .. tags.

Now when I do this:

<td>{{ object.content|raw  }}</td>

He shows the string without the <p> tags. But when I add the slice filter it doesn't work ... I also tried to set a variable before the output like this:

{% set rawcontent = object.content %}
<td>{{ rawcontent|slice(0, 50) ~ '...'  }}</td>

But same result... How can I fix this?

like image 500
nielsv Avatar asked Jan 16 '15 14:01

nielsv


People also ask

What is raw in twig?

3. raw. By default, everything in Twig gets escaped when automatic escaping is enabled. If you don't want to escape a variable you'll have to explicitly mark it as safe which you can do by using the raw filter.

What are twig filters in Drupal?

Filters in Twig can be used to modify variables. Filters are separated from the variable by a pipe symbol. They may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.


2 Answers

striptags should be used here instead of raw

object.content|striptags|slice(0, 50)

See fiddle

like image 114
smarber Avatar answered Sep 24 '22 00:09

smarber


A filter is dedicated to this kind of behavior : truncate() It is disabled but you can activate it :

services:
   twig.extension.text:
      class: Twig_Extensions_Extension_Text
      tags:
          - { name: twig.extension }

And you can use it like this:

{{ entity.text|striptags|truncate(50, true, "...")|raw }}

The best use is when you want to limit character with HTML content.

  1. You remove tags in order to note apply it with 'striptags'
  2. You interprate the html entities like '&eacute' with 'raw'
  3. you can count and truncate the real size of your string ;)

    {% if entity.contenu|striptags|raw|length > 50 %}
                    {{ entity.contenu|striptags|truncate(50, true, "...")|raw }}
                {% else %} 
                    {{ entity.contenu|striptags|raw }}
                {% endif %}
    

Or you can use it like this:

{{ entity.text|striptags|length > 50 ? entity.text|striptags|truncate(50, true, "...")|raw  : entity.text|striptags|raw }}

Hope that help...

like image 38
chadyred Avatar answered Sep 25 '22 00:09

chadyred