Twig is_safe对于简单函数不起作用

twig is_safe for simple function does not work

本文关键字:简单 函数 不起作用 于简单 is safe Twig      更新时间:2023-09-26

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

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

如何解决这个问题?

我的简单函数:

<?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'))),

我想,在你的情况下,你应该选择'is_safe' => ['js']。如果由于某种原因没有帮助,您可以使用Twig的过滤器raw中的定义,其中将is_safe定义为all