带有 Symfony 2 的 Twig 显示 prod 和 dev 之间不同的 json 编码变量 [英] Twig with Symfony 2 displaying json encoded variables different between prod and dev

查看:23
本文介绍了带有 Symfony 2 的 Twig 显示 prod 和 dev 之间不同的 json 编码变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在构建一个 Symfony 2 应用程序,它将一些数据从控制器发送到视图:

We're building a Symfony 2 application that sends some data from controller to view:

$user = array(
    'configuration' => array(
        'levels' => array(
            'warning' => 0.05,
            'danger'  => 0.10,
        ),
    ),
);

return $this->render(
    'MyWebsiteBundle:Core:searchResults.html.twig',
    array(
        'userJSON'  => json_encode($user)
    )
);

查看

<script language="javascript">
    user = $.parseJSON("{{ userJSON }}");
</script>

结果

dev 上,结果如下所示并且按预期工作:

Result

On dev the result looks like this and works as expected:

user = $.parseJSON("x7Bx22configurationx22x3Ax7Bx22levelsx22x3Ax7Bx22warningx22x3A0.05,x22dangerx22x3A0.1x7Dx7Dx7D");

另一方面,在 prod 上,结果以不同的方式编码,因此在控制台中显示错误:

On the other hand, on prod the result is encoded in a different manner, thus displaying errors in console:

user = $.parseJSON("{&quot;configuration&quot;:{&quot;levels&quot;:{&quot;warning&quot;:0.05,&quot;danger&quot;:0.1}}}");

控制台错误:Uncaught SyntaxError: Unexpected token &

Console Error: Uncaught SyntaxError: Unexpected token &

是什么产生了这种差异?

What generates this difference?

推荐答案

还要检查下面@Lulhum 的解决方案.如果它更好,请投票,所以我会选择它作为正确答案.

Also check @Lulhum's solution below. Up-vote it if it's better so I will select it as the correct answer.

问题"是 Twig 自动转义变量.我使用 Twig 的 raw 过滤器来跳过自动转义,如下所示:

The "problem" was Twig autoescaping variables. I used Twig's raw filter to skip autoescaping like this:

<script language="javascript">
    user = $.parseJSON('{{ userJSON | raw }}');
</script>

现在打印出来了:

user = $.parseJSON('{"configuration":{"levels":{"warning":0.05,"danger":0.1}}}');

链接:Symfony 2 Docs - 输出转义

这篇关于带有 Symfony 2 的 Twig 显示 prod 和 dev 之间不同的 json 编码变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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