Twig with Symfony 2 displaying json encoded variables different between prod and dev

12,173

Solution 1

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

Solution 2

It is better to avoid using the raw filter when possible. You can here achieve the same behavior with the escape filter (doc).

<script language="javascript">
    user = $.parseJSON('{{ userJSON | escape('js') }}');
</script>
Share:
12,173

Related videos on Youtube

VMC
Author by

VMC

Updated on June 04, 2022

Comments

  • VMC
    VMC almost 2 years

    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?

  • Kvn91
    Kvn91 almost 8 years
    gosh you just saved my life ! was trying 1000 solutions and in fact I just replaced "raw" by "escape('js')" and it worked fine ! Thx
  • Vincent Decaux
    Vincent Decaux over 4 years
    Same for me ! even if the printed string is impossible to read for human, works like a charm