nielsv
nielsv

Reputation: 6800

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?

Upvotes: 9

Views: 11855

Answers (4)

ACFK
ACFK

Reputation: 66

I tried Max Lipsky's code, then i noticed it doen't work for characters like &atilde; then i modified it a little and now it seems to work just fine

{{ event.info|striptags|length > 150 ? event.info|raw|slice(0,150)|raw : event.info|raw }}
{{ event.info|striptags|length > 150 ? '...' : ''}}

Upvotes: 3

chadyred
chadyred

Reputation: 472

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...

Upvotes: 7

Max Lipsky
Max Lipsky

Reputation: 1842

I tried use "raw", "slice" and "~" in various combination. It doesn't working together correctly (and "striptags" too). You can use only "raw" and "slice" together.

So I found other method(looks no good, but it work):

{{ event.info|length > 300 ? event.info|slice(0,300)|raw : event.info|raw }}
{{ event.info|length > 300 ? '...' : ''}}

Upvotes: 2

smarber
smarber

Reputation: 5074

striptags should be used here instead of raw

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

See fiddle

Upvotes: 22

Related Questions