Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig striptags and html special chars

I am using twig to render a view and I am using the striptags filter to remove html tags. However, html special chars are now rendered as text as the whole element is surrounded by "". How can I either strip special chars or render them, while still using the striptags function ?

Example :

{{ organization.content|striptags(" >")|truncate(200, '...') }}

or

{{ organization.content|striptags|truncate(200, '...') }}

Output:

"QUI SOMMES NOUS ? > NOS LOCAUXNOS LOCAUXDepuis 1995,  Ce lieu chargé d’histoire et de tradition s’inscrit dans les valeurs"
like image 221
Sébastien Avatar asked Feb 23 '15 09:02

Sébastien


4 Answers

If it could help someone else, here is my solution

{{ organization.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}

You can also add a trim filter to remove spaces before and after. And then, you truncate or slice your organization.content

EDIT November 2017

If you want to keep the "\n" break lines combined with a truncate, you can do

{{ organization.content|striptags|truncate(140, true, '...')|raw|nl2br }}

like image 91
Elyass Avatar answered Nov 17 '22 00:11

Elyass


I had a similar issue, this worked for me:

{{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}
like image 33
Jon Avatar answered Nov 17 '22 00:11

Jon


I was trying some of, among others, these answers:

{{ organization.content|striptags|truncate(200, true) }}
{{ organization.content|raw|striptags|truncate(200, true) }}
{{ organization.content|striptags|raw|truncate(200, true) }}
etc.

And still got strange characters in the final form. What helped me, is putting the raw filter on the end of all operations, i.e:

{{ organization.content|striptags|truncate(200, '...')|raw }}
like image 6
Jazi Avatar answered Nov 17 '22 00:11

Jazi


Arf, I finally found it :

I am using a custom twig filter that just applies a php function:

<span>{{ organization.shortDescription ?: php('html_entity_decode',organization.content|striptags|truncate(200, '...')) }}</span>

Now it renders correctly

My php extension:

<?php

namespace AppBundle\Extension;

class phpExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('php', array($this, 'getPhp')),
        );
    }

    public function getPhp($function, $variable)
    {
        return $function($variable);
    }

    public function getName()
    {
        return 'php_extension';
    }
}
like image 5
Sébastien Avatar answered Nov 17 '22 00:11

Sébastien