Unescape 或 html 解码

问题描述 投票:0回答:4
php twig
4个回答
62
投票

您可以使用

raw
过滤器使 twig 渲染原始 HTML。

{% autoescape %}
    {{ var|raw }} {# var won't be escaped #}
{% endautoescape %}

来源


18
投票

使用 |raw 时应小心。说数据是安全的,意味着您 100% 信任它。

我个人建议使用自定义树枝过滤器:

class CustomExtension extends \Twig_Extension 
{
    public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('unescape', array($this, 'unescape')),
        );
    }

    public function unescape($value)
    {
        return html_entity_decode($value);
    }
}

将以下内容添加到您的 services.yml(或者翻译为 xml)。

 services:
     ha.twig.custom_extension:
     class: HA\SiteBundle\Twig\CustomExtension
     tags:
         - { name: twig.extension }

16
投票

http://twig.sensiolabs.org/doc/filters/raw.html

{% autoescape false %}
   {{ your_item }}{# your_item won't be escaped #}
{% endautoescape %}

5
投票

如果您使用 Drupal 8 并且

raw
autoscape
都不起作用,则可能会发生这种情况,因为您尝试打印的变量是一个包含安全输出模板的渲染数组(例如,一个
 hl2br
过滤器)。

在这种情况下,您需要通过渲染数组访问该值并对其进行过滤,例如:

{% autoescape false %}
  {{ item.content['#context']['value'] }}
{% endautoescape %}
© www.soinside.com 2019 - 2024. All rights reserved.