在 Twig 中设置默认原始过滤器 [英] Set default raw filter in Twig

查看:28
本文介绍了在 Twig 中设置默认原始过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Silex 构建一个站点,并使用 Twig 来显示基于 json 文件的内容.

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

这是控制器中的代码:

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

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

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

});

Data 只是一个自定义类,它将要显示的页面和要使用的语言作为参数,并根据 Twig 用作页面数据的 json 文件返回一个数组.

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.

问题在于 json 文件包含 HTML 标签,当 Twig 呈现页面时,它会将它们显示为实体,例如,我的 test.html 模板如下所示:

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>

但是在 {{ bannerTitle }} 上输出以下内容:

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

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

查看源代码如下:

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

但我想尽可能保持模板上的代码干净,并避免将 raw 放在模板上的所有内容中.

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

有没有办法告诉 Twig 始终将生成的输出视为原始输出?

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

P.S:我也尝试用 htmlentities、html_entity_decode 等解析生成的数据,但没有成功:(

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

推荐答案

我很确定这可以通过在 twig 中使用 {% autoescape false %} {% endautoescape %} 标签来实现.

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

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

更多信息请访问http://twig.sensiolabs.org/doc/tags/autoescape.html

如果没有给 {% filter raw %} {% endfilter %} 一个合适的位置,这应该可以避免您将 |raw 添加到每个变量.使用这两种方法中的任何一种,只要记住 |escape 任何可能需要它的变量.

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.

这篇关于在 Twig 中设置默认原始过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆