Twig扩展禁用自动转义
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Twig扩展禁用自动转义相关的知识,希望对你有一定的参考价值。
我做了一个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
AppExtensionFrontendTwigExtension:
arguments:
- '@AppDataProviderDataProviderService'
tags:
- { name: 'twig.extension' }
答案
您需要设置is_safe
选项:
['needs_environment' => true, 'is_safe' => ['html']]
另一答案
尝试在树枝上使用raw
功能。
{% extends 'base.html.twig' %}
{% block pageHeader %}
{{ getPageHeader()|raw }}
{{ getProductDetailData()|raw }}
{% endblock %}
来源:https://twig.symfony.com/doc/2.x/filters/raw.html
以上是关于Twig扩展禁用自动转义的主要内容,如果未能解决你的问题,请参考以下文章