We're building a Symfony 2 application that sends some data from controller to view:
我们正在构建一个Symfony 2应用程序,将一些数据从控制器发送到视图:
Controller
$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)
)
);
View
<script language="javascript">
user = $.parseJSON("{{ userJSON }}");
</script>
Result
On dev
the result looks like this and works as expected:
在dev中,结果如下所示:
user = $.parseJSON("\x7B\x22configuration\x22\x3A\x7B\x22levels\x22\x3A\x7B\x22warning\x22\x3A0.05,\x22danger\x22\x3A0.1\x7D\x7D\x7D");
On the other hand, on prod
the result is encoded in a different manner, thus displaying errors in console:
另一方面,在prod上,结果以不同的方式编码,从而在控制台上显示错误:
user = $.parseJSON("{"configuration":{"levels":{"warning":0.05,"danger":0.1}}}");
Console Error: Uncaught SyntaxError: Unexpected token &
控制台错误:未捕获的SyntaxError:意外令牌&。
What generates this difference?
会产生这种差异呢?
2 个解决方案
#1
19
Edit: Also check @Lulhum's solution below. Up-vote it if it's better so I will select it as the correct answer.
编辑:也检查@Lulhum的解决方案。如果是更好的,请向上投票,因此我将选择它作为正确的答案。
The "problem" was Twig autoescaping variables. I used Twig's raw
filter to skip autoescaping like this:
“问题”是Twig自动转义变量。我使用Twig的原始过滤器来跳过这样的自动转义:
<script language="javascript">
user = $.parseJSON('{{ userJSON | raw }}');
</script>
Now it prints:
现在它打印:
user = $.parseJSON('{"configuration":{"levels":{"warning":0.05,"danger":0.1}}}');
Links: Symfony 2 Docs - Output escaping
链接:Symfony 2文档-输出转义
#2
4
It is better to avoid using the raw
filter when possible. You can here achieve the same behavior with the escape
filter (doc).
最好尽可能避免使用原始过滤器。您可以使用escape过滤器(doc)实现相同的行为。
<script language="javascript">
user = $.parseJSON('{{ userJSON | escape('js') }}');
</script>
#1
19
Edit: Also check @Lulhum's solution below. Up-vote it if it's better so I will select it as the correct answer.
编辑:也检查@Lulhum的解决方案。如果是更好的,请向上投票,因此我将选择它作为正确的答案。
The "problem" was Twig autoescaping variables. I used Twig's raw
filter to skip autoescaping like this:
“问题”是Twig自动转义变量。我使用Twig的原始过滤器来跳过这样的自动转义:
<script language="javascript">
user = $.parseJSON('{{ userJSON | raw }}');
</script>
Now it prints:
现在它打印:
user = $.parseJSON('{"configuration":{"levels":{"warning":0.05,"danger":0.1}}}');
Links: Symfony 2 Docs - Output escaping
链接:Symfony 2文档-输出转义
#2
4
It is better to avoid using the raw
filter when possible. You can here achieve the same behavior with the escape
filter (doc).
最好尽可能避免使用原始过滤器。您可以使用escape过滤器(doc)实现相同的行为。
<script language="javascript">
user = $.parseJSON('{{ userJSON | escape('js') }}');
</script>