【问题标题】:twig is_safe for simple function does not work用于简单功能的 twig is_safe 不起作用
【发布时间】: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


    【解决方案1】:

    您已在回调中包含您的 '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'))),
    

    【讨论】:

    • 刚刚犯了同样的错误。你节省了我的时间。
    【解决方案2】:

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

    【讨论】:

    • 好吧,将这个 'html' 值更改为 'js' 或 'all' 不会改变任何东西:js 显示为纯文本而不是执行,而使用 raw 过滤器确实有效.. .我仍然被困在这里。知道要测试什么以更好地理解问题吗?
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2011-09-10
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多