gpt4 book ai didi

javascript - 简单功能的 twig is_safe 不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 04:16:06 24 4
gpt4 key购买 nike

我已经创建了一个简单的函数来使用 js 呈现模板。我希望它自动转义,所以我已经将 is_safe 参数设置为 array(html') 以不必使用 |raw 过滤器

但是它不起作用,jsis 没有转义而是呈现为纯文本。如果我使用 |raw 过滤器,它工作得很好。

我该如何解决这个问题?

我的简单功能:

<?php

namespace AppBundle\Extension\Twig;

use AppBundle\FoodMeUpParameters;
use AppBundle\Model\Interfaces\ViewCountInterface;
use ReflectionClass;
use Symfony\Component\DependencyInjection\ContainerInterface;

class FMUTwigExtension extends \Twig_Extension
{
/**
* @var ContainerInterface
*/
private $container;

public function setContainer(ContainerInterface $container)
{
$this->container = $container;
}

public function getFunctions()
{
return array(
'increaseViewCount' => new \Twig_SimpleFunction('increaseViewCount', array($this, 'increaseViewCount', array('is_safe' => array('html')))),
);
}


public function increaseViewCount(ViewCountInterface $entity, $andFlush = true)
{
$reflect = new ReflectionClass($entity);

$parameters = array(
'short_name' => $reflect->getShortName(),
'identifier' => $entity->getId(),
'and_flush' => $andFlush
);

return $this->container->get('templating')->render(':Helper:increase_view_count.htmpl.twig', $parameters);
}
}

我的模板:

<script>
$(function(){
$.ajax({
url: '{{ path('increase_view_count') }}',
type: "post",
dataType: "json",
data: {shortName: '{{ short_name }}', identifier: '{{ identifier }}', andFlush: '{{ and_flush }}'},
success: function (result) {
console.log(result);
}
});
});
</script>

服务声明

fmu_twig_extension:
class: %fmu_twig_extension.class%
calls:
- [setContainer, [@service_container]]
tags:
- { name: twig.extension }

最佳答案

您在回调中包含了您的 'is_safe' 选项,而不是在下一个 ($options) 参数中。

你需要改变......

'increaseViewCount' => new \Twig_SimpleFunction('increaseViewCount', array($this, 'increaseViewCount', array('is_safe' => array('html')))),

...到...

'increaseViewCount' => new \Twig_SimpleFunction('increaseViewCount', array($this, 'increaseViewCount'), array('is_safe' => array('html'))),

关于javascript - 简单功能的 twig is_safe 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com