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?
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.
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.
striptags
should be used here instead of raw
object.content|striptags|slice(0, 50)
See fiddle
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With