twig striptags and html special chars

前端 未结 5 1585
小蘑菇
小蘑菇 2021-01-04 00:23

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 surrou

相关标签:
5条回答
  • 2021-01-04 00:37

    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';
        }
    }
    
    0 讨论(0)
  • 2021-01-04 00:39

    I had a similar issue, this worked for me:

    {{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}
    
    0 讨论(0)
  • 2021-01-04 00:48

    I had the same problem, I resolved it byt this function below, using strip_tags.

    <?php
    
    namespace AppBundle\Extension;
    
    class filterHtmlExtension extends \Twig_Extension
    {
    
        public function getFunctions()
        {
            return array(
                new \Twig_SimpleFunction('stripHtmlTags', array($this, 'stripHtmlTags')),
            );
        }
    
    
        public function stripHtmlTags($value)
        {
    
            $value_displayed = strip_tags($value);
    
    
            return $value_displayed ;
        }
    
        public function getName()
        {
           return 'filter_html_extension';
        }
    }
    
    0 讨论(0)
  • 2021-01-04 00:50

    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 }}
    
    0 讨论(0)
  • 2021-01-04 00:54

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

    0 讨论(0)
提交回复
热议问题