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>
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("{"configuration":{"levels":{"warning":0.05,"danger":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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With