Julien Lamarche
Julien Lamarche

Reputation: 1050

How to create custom escape strategy escaping only double quote (for json) in symfony & twig?

A customer wants double quotes and only double quotes escaped for a json output. This means single quotes should not be escaped as per the default twig html escape strategy, for example:

"2565": "Fête Médiéval du Royaume d'Osgoode "

The 'js' escape strategy does not fit the bill as it escapes all non-alphanumeric characters. From Symfony/vendor/twig/twig/lib/Twig/Extension/Core.php

    case 'js':
        // escape all non-alphanumeric characters
        // into their \xHH or \uHHHH representations

I thought creating a custom escaping strategy would be the best way to go about it (perhaps it wasn't, but that's not the end question of this post :-) ). But how to create the custom strategy and more importantly, how to inject it in the twig environment via Symfony?

Upvotes: 1

Views: 2155

Answers (2)

Ian Phillips
Ian Phillips

Reputation: 2057

To extend Julien's answer... The way to set the default autoescape for all templates is:

$twig->getExtension('escaper')->setDefaultStrategy('json');

Upvotes: 0

Julien Lamarche
Julien Lamarche

Reputation: 1050

In a class extending Symfony\Bundle\FrameworkBundle\Controller\Controller, the twig environment can first be obtained via the container property of the Controller class:

    $twig   = $this->container->get('twig');

The setEscaper method can then be used to create the strategy with a callable:

    $twig->getExtension('core')->setEscaper('json', function($twigEnv, $string, $charset) {
        return addcslashes($string, '"');
    });

In your twig template, set the autoescape strategy

{% autoescape 'json' %}
... (json template and twig code) ...
{% endautoescape %}

I'm assuming there is a way of setting the default autoescape for all twig templates. However in my case some twig templates returned xml instead of json.

Upvotes: 2

Related Questions