Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig is_safe for simple function does not work

I have created a simple function that renders a template with js. I'd like it to autoescape so I have set up the is_safe parameter to array(html') to not have to use the |raw filter

However it does not work, the jsis not escaped but rendered as plain text. If I use the |raw filters it works just fine.

How can I solve this ?

My simple function:

<?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);
    }
}

My template :

<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>

The service declaration

fmu_twig_extension:
    class: %fmu_twig_extension.class%
    calls:
        - [setContainer, [@service_container]]
    tags:
        - { name: twig.extension }
like image 242
Sébastien Avatar asked May 18 '15 08:05

Sébastien


1 Answers

You've included your 'is_safe' options in your callback, rather than in the next ($options) argument.

You need to change....

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

... to ...

'increaseViewCount' => new \Twig_SimpleFunction('increaseViewCount', array($this, 'increaseViewCount'), array('is_safe' => array('html'))),
like image 55
TobyG Avatar answered Oct 19 '22 20:10

TobyG