您可以使用
raw
过滤器使 twig 渲染原始 HTML。
{% autoescape %}
{{ var|raw }} {# var won't be escaped #}
{% endautoescape %}
使用 |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 }
或http://twig.sensiolabs.org/doc/filters/raw.html
{% autoescape false %}
{{ your_item }}{# your_item won't be escaped #}
{% endautoescape %}
如果您使用 Drupal 8 并且
raw
或 autoscape
都不起作用,则可能会发生这种情况,因为您尝试打印的变量是一个包含安全输出模板的渲染数组(例如,一个 hl2br
过滤器)。
在这种情况下,您需要通过渲染数组访问该值并对其进行过滤,例如:
{% autoescape false %}
{{ item.content['#context']['value'] }}
{% endautoescape %}