twig striptags和html特殊字符

时间:2015-02-23 09:08:25

标签: html symfony twig special-characters strip

我正在使用twig渲染视图,我正在使用striptags过滤器来删除html标记。 但是,html特殊字符现在呈现为文本,因为整个元素被“”包围。 我怎样才能剥离特殊字符或渲染它们,同时仍然使用striptags函数?

示例:

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

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

输出:

"QUI SOMMES NOUS ? > NOS LOCAUXNOS LOCAUXDepuis 1995,  Ce lieu chargé d’histoire et de tradition s’inscrit dans les valeurs"

6 个答案:

答案 0 :(得分:33)

如果它可以帮助别人,这是我的解决方案

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

您还可以添加修剪滤镜以删除前后的空格。 然后,您截断或切片您的organization.content

2017年11月编辑

如果要将“\ n”断行与截断相结合,可以执行

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

答案 1 :(得分:5)

我有类似的问题,这对我有用:

{{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}

答案 2 :(得分:3)

Arf,我终于找到了它:

我正在使用一个只应用php函数的自定义树枝过滤器:

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

现在渲染正确

我的php扩展程序:

<?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';
    }
}

答案 3 :(得分:2)

我正在尝试其中一些答案:

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

在最终形式中仍然有奇怪的角色。帮助我的是,raw过滤器在所有操作结束时,即:

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

答案 4 :(得分:0)

我有同样的问题,我使用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';
    }
}

答案 5 :(得分:0)

最好的方法是:

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

总是以 |raw 结尾。

不要使用 convert_encoding('UTF-8', 'HTML-ENTITIES'),您会遇到 iconv 问题。