Set default raw filter in Twig

删除回忆录丶 提交于 2020-01-24 08:41:27

问题


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


回答1:


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.




回答2:


You shouldn't pass HTML as data to a template engine. If the JSON has the tags, then you will need to put |raw after every variable unfortnately. Twig probably does this for security reasons.

Otherwise:

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

    <span class='title light'>{{ bannerTitle }}</span>

</body>

Now all you need to pass in is:

Array(
    'bannerTitle' => 'Contact Us'
)


来源:https://stackoverflow.com/questions/22185878/set-default-raw-filter-in-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!