tonyRICHER
tonyRICHER

Reputation: 87

How to pass array from Twig to Javascript using JSON

I need your help to work miracles.

I want to convert Twig array to Javascript array and then use it in a loop and create markers for the Google API.

<script>
    var map, marker, i, e;
    var companies = {{ companies.items | json_encode() | raw }};

    console.log(companies);
    var address = {{ search.city.first.name | json_encode() | raw }};

    function initMap() {
        var geocoder = new google.maps.Geocoder();

        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 44.8333, lng: -0.5667},
            zoom: 12,
            disableDefaultUI: true
        });

        //for (i = 0; i < locations.length; i++) {
            //marker = new google.maps.Marker({
                //position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                //map: map
            //});

    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEYLOL&callback=initMap"></script>

When I get my array back, companies show me an empty array.

Screen of empty array of console.log(companies)

But when I dump this on twig my array is ok ..

Dump array on Twig

Can someone help me?

Upvotes: 2

Views: 3709

Answers (2)

tonyRICHER
tonyRICHER

Reputation: 87

I put all my values into a hidden input. And I get it in json at last I JSON.parse my Json result. It's not perfect but it's working.

My Twig code :

{% set array = [] %}
  {% for company in companies %}
    {% set array = array | merge([{name: company.title, latitude: company.latitude, longitude: company.longitude}]) %}
  {% endfor %}
  <input type="hidden" id="array" value="{{ array|json_encode }}">

My javascript :

<script>
    var map, marker, i;
    var array = document.getElementById('array').value;
    var companies = JSON.parse(array);

    var address = {{ search.city.first.name | json_encode() | raw }};

    function initMap() {
        var geocoder = new google.maps.Geocoder();

        map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 44.8333, lng: -0.5667},
            zoom: 14,
        });

        geocoder.geocode({'address': address}, function (results, status) {
            if (status === 'OK') {
                map.setCenter(results[0].geometry.location);
            } else {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });

        for (i = 0; i < companies.length; i++) {
            marker = new google.maps.Marker({
                position: new google.maps.LatLng(companies[i].latitude, companies[i].longitude),
                map: map
            });

            google.maps.event.addListener(marker, 'click', (function(marker, i) {
                return function() {
                    infowindow.setContent(companies[i].name);
                    infowindow.open(map, marker);
                }
            })(marker, i));
        }
    }
</script>

Upvotes: 0

Jakumi
Jakumi

Reputation: 8374

json_encode will by default serialize an object by outputting all public (i.e. accessible) properties. Since your objects have no public properties, the serialization is empty. you could implement the JsonSerializable interface. (IMHO, the simplest solution)

There are other more complicated ways to achieve this. They become relevant if the json serialization will vary on context .... Alternatives would be to implement a twig function that will fetch certain fields from your objects, writing a proper serializer or implementing functions on your objects that expose the proper serialization depending on context.

Upvotes: 2

Related Questions