Twig扩展禁用自动转义

问题描述 投票:0回答:2

我做了一个twig扩展,可以调用模板中的函数,但不幸的是现在这些函数的渲染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' }
symfony twig escaping symfony4 twig-extension
2个回答
1
投票

您需要设置is_safe选项:

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

-1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.