带有 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("{"configuration":{"levels":{"warning":0.05,"danger":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 - 输出转义
相关文章