【发布时间】:2015-05-18 08:56:18
【问题描述】:
我创建了一个简单的函数,用 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 }
【问题讨论】:
标签: javascript symfony filter escaping twig