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

问题描述

我们正在建立一个Symfony 2应用程序,从控制器发送一些数据:



控制器



<$ (
'levels'=>数组(
'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 结果看起来像这样,按预期工作:

  user = $ .parseJSON \x7B\x22configuration\x22\x3A\x7B\x22levels\x22\x3A\x7B\x22warning\x22\x3A0.05,\x22danger\x22\x3A0。 1\x7D\x7D\x7D); 

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

  user = $ .parseJSON({&配置&安培; QUOT;:{&安培; QUOT;水平&安培; QUOT;:{&安培; QUOT;警告&安培; QUOT;:0.05,&安培; QUOT;危险&安培; QUOT;:0.1}}}); 

控制台错误:未捕获语法错误:意外的令牌&



什么产生这种差异?

解决方案

编辑:还请查看@ Lulhum的解决方案。如果它更好的话,最好选择它,所以我将选择它作为正确的答案。



问题是Twig自变量变量。我使用Twig的原始过滤器来跳过自动转义:

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

现在打印:

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

链接:


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?

解决方案

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

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>

Now it prints:

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

Links:Symfony 2 Docs - Output escaping

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

08-04 12:40