2015-02-23 124 views
9

我正在使用树枝来呈现一个视图,我使用striptags过滤器来删除html标签。 但是,html特殊字符现在呈现为文本,因为整个元素被“”包围。 如何在剥离特殊字符或呈现它们的同时仍使用striptags功能?枝条标签和html特殊字符

例子:

{{ 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" 
+0

没有工作,但我终于解决了。谢谢! – 2015-02-23 09:14:57

回答

2

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

我有同样的问题,我解决它BYT低于这个功能,使用用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'; 
    } 
} 
22

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

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

您也可以前后添加一个调整滤波器去除空间。 然后,你如果你想保持“\ n”破线用截相结合,你可以做截断或切片您organization.content

编辑2017年11月

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

+0

非常感谢您的回答:简短,简洁,正是我所搜索的内容。 – nicolallias 2016-04-12 15:58:30

+3

我还在弄些奇怪的特殊字符,所以我尝试了其他一些东西。这对我很有用: '{{organization.content | striptags | raw}}' – 2016-06-09 20:16:58

+0

请小心使用raw,因为它可能存在XSS问题。另请参阅https://github.com/twigphp/Twig/issues/2215#issuecomment-258088927 – LarS 2017-08-21 17:35:48

1

我尝试了一些,等等,这些问题的答案:

{{ 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 }} 
+0

请小心使用raw,因为它可能存在XSS问题。另请参阅https:// github。com/twigphp/Twig/issues/2215#issuecomment-258088927 – LarS 2017-08-21 17:35:08

+0

是的,但我首先使用'striptags'。它不确保它会安全吗? – 2017-08-22 11:45:05

+1

我为某些标签仍然可以被允许的情况添加了警告。没有允许标签的'striptags'会保存保存,但是带有允许的标签'striptags('<允许标签>')'不。它在内部使用php函数strip_tags,另请参阅https://stackoverflow.com/q/3605629/880188。 – LarS 2017-08-23 11:54:04

3

我有一个类似的问题,这个工作对我来说:

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

这也适用于我。 – 2017-09-11 13:20:08