Twig pass parameters to JS as JSON

I’m currently working on a mini web project it’s a sort of an escape game, and I’m using Symfony framework, and this framework is new to me so basically I’m learning how to use via this project I’m blocked by a little problem, i can’t figure out how to pass data to the JS external code,
I use return $this->render("app/player_interface.html.twig",['player'=>$player]); in the Symfony controller to send the player object to the twig and then in the twig I inserted this block

      {% set player_data = {
                pseudo: player.Username,
                longitude: player.longitude,
                latitude: player.latitude,

            } %}

    <div data-player='{{ player|json_encode|raw }}'>

and then in the javascript file is use this:

const player_data =document.querySelectorAll('[data-player]');
const playerObject =Array.from(player_data).map(item => JSON.parse(item.dataset.player));

But the console log is showing me an empty array and even if I print the player_data variable which is supposed to be a JSON file the console shows me an empty node, I looked in many website and the Symfony documentation but I can’t find any good detailed example.

I hope that you could help me and thanks in advance.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *