Twig Extension禁用自动转义

时间:2018-09-04 08:24:33

标签: symfony twig escaping symfony4 twig-extension

我做了一个小树枝扩展,可以在模板中调用函数,但是不幸的是,现在这些函数的html内容已转义。你知道我如何禁用它吗?

FrontendTwigExtension.php

class FrontendTwigExtension extends Twig_Extension
{
/**
 * @var DataProviderService
 */
private $dataProvider;

/**
 * FrontendTwigExtension constructor.
 * @param DataProviderService $dataProvider
 */
public function __construct(DataProviderService $dataProvider)
{
    $this->dataProvider = $dataProvider;
}

/**
 * @return array
 */
public function getFunctions(): array
{
    return array(
        new Twig_Function('getProductDetailData',
            [$this, 'getProductDetailData'],
            ['needs_environment' => true]
        ),
        new Twig_Function('getPageHeader',
            [$this, 'getPageHeader'],
            ['needs_environment' => true]
        )
    );
}

/**
 * @param Twig_Environment $env
 * @return string
 * @throws Twig_Error_Loader
 * @throws Twig_Error_Runtime
 * @throws Twig_Error_Syntax
 */
public function getPageHeader(Twig_Environment $env): string
{
    return $env->render('Component/PageHeader/pageHeader.html.twig');
}

/**
 * @param Twig_Environment $env
 * @return string
 * @throws Twig_Error_Loader
 * @throws Twig_Error_Runtime
 * @throws Twig_Error_Syntax
 */
public function getProductDetailData(Twig_Environment $env): string
{
    $service = new ProductDetailDataService($this->dataProvider);
    return $env->render('Module/ProductDetailPage/productDetailData.html.twig',
        [
            'productData' => $service->getData()
        ]
    );
}
}

template.html.twig

{% extends 'base.html.twig' %}
{% block pageHeader %}
    {{ getPageHeader() }}
    {{ getProductDetailData() }}
{% endblock %}

services.yaml

App\Extension\FrontendTwigExtension:
    arguments:
        - '@App\DataProvider\DataProviderService'
    tags:
        - { name: 'twig.extension' }

2 个答案:

答案 0 :(得分:1)

您需要设置is_safe选项:

['needs_environment' => true, 'is_safe' => ['html']]

答案 1 :(得分:-1)

尝试在树枝中使用raw功能。

{% extends 'base.html.twig' %}
{% block pageHeader %}
    {{ getPageHeader()|raw }}
    {{ getProductDetailData()|raw }}
{% endblock %}

来源:https://twig.symfony.com/doc/2.x/filters/raw.html