Twig is_safe for simple function doesn't work
I have created a simple function that renders a template with js. I would like it to be in autoescape, so I set the is_safe parameter to array (html ') to not use the filter
However, this does not work, jsis is not escaped but is displayed as plain text. If I use raw filters it works 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>
Service declaration
fmu_twig_extension:
class: %fmu_twig_extension.class%
calls:
- [setContainer, [@service_container]]
tags:
- { name: twig.extension }
source to share
I realize this is a bit old-fashioned now, but you included the "is_safe" options in your callback, not in the next argument ($ options).
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'))),
source to share
I suppose in your case you should choose 'is_safe' => ['js']
. If for some reason this does not help, you can use the definition from the Twig filter raw
where it is defined is_safe
asall
.
source to share