Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default raw filter in Twig

I'm using Silex to build a site and Twig to display the contents based on a json file.

Here's the code in the controller:

$app->get('/', function() use ($app) {

    $data = $app['data']->get('contactUs', 'es');

    return $app['twig']->render('test.html', $data);

});

Datais just a custom class that takes as argument the page to be displayed and the language to use and returns an array based on the json file that Twig uses as the data on the page.

The problem is that the json file contains HTML tags, and when Twig renders the page it displays them as entities, for example, my test.html template looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Twit Test</title>
    </head>
<body>

    {{ bannerTitle }}

</body>
</html>

But that outputs the following on {{ bannerTitle }} :

<span class='title light'>Contact Us</span>

Which by looking at the source code looks like this:

&lt;span class=&#039;title light&#039;&gt;Contacto y&lt;/span&gt;&lt;br&gt;&lt;span class=&#039;title&#039;&gt;Ubicación&lt;/span&gt;

I look around at the docs, and I know I can use the raw filter on the template to avoid this, like this:

{{ bannerTitle|raw }}

But I want to keep as clean as possible the code on the templates, and avoid putting rawto everything on the templates.

Is there a way to tell Twig to treat always as raw the generated output?

P.S: I also tried parsing the generated data with htmlentities, html_entity_decode, etc with no luck :(

like image 696
arielcr Avatar asked Mar 05 '14 00:03

arielcr


1 Answers

I'm pretty sure this is possible by using the {% autoescape false %} {% endautoescape %} tags in twig.

i.e.

{% autoescape false %}
<!DOCTYPE html>
<html>
    <head>
        <title>Twit Test</title>
    </head>
    <body>
        {{ bannerTitle }}
        {{ moreHTMLdata }}
        {{ evenMoreHTMLdata }} 
    </body>
</html>
{% endautoescape %}

More info at http://twig.sensiolabs.org/doc/tags/autoescape.html

Failing that give {% filter raw %} {% endfilter %} a go in it's place and this should save you having to add |raw to every variable. Using either of these methods, just remember to |escape any variables which might need it.

like image 153
Ian Belcher Avatar answered Oct 01 '22 12:10

Ian Belcher