9

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

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:

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:

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

Console Error: Uncaught SyntaxError: Unexpected token &

What generates this difference?

4

2 回答 2

19

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

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

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

现在它打印:

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

链接: Symfony 2 Docs - 输出转义

于 2013-10-25T21:32:13.880 回答
6

最好尽可能避免使用raw过滤器。您可以在此处使用escape过滤器 ( doc ) 实现相同的行为。

<script language="javascript">
    user = $.parseJSON('{{ userJSON | escape('js') }}');
</script>
于 2016-06-02T10:46:04.787 回答