How to use Laravel Blade in a script file?


I am trying to make a store locator app using this tutorial and Laravel 5. People in these questions Here and Here seem to be using @foreach loops and other blade templating language to run through their lat/long coordinates. How are they doing that?

I basically do not know how to loop through coordinates using blade when my map code is in a js file? How is that possible? Am I doing something totally wrong?

I am showing my map with a js file (maps.js) that has the following code:

function initialize() {

var map_canvas = document.getElementById('map');

// Initialise the map
var map_options = {
    center: location,
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)

// Put all locations into array
var locations = [
@foreach ($articles as $article)
    [ {{ $article->lat }}, {{ $article->lng }} ]     
@endforeach
];

for (i = 0; i < locations.length; i++) {
    var location = new google.maps.LatLng(locations[i][0], locations[i][1]);

    var marker = new google.maps.Marker({
        position: location,
        map: map,
    }); 
}

// marker.setMap(map); // Probably not necessary since you set the map above

}

But obviously that gets stuck on the @foreach line.

PS: If anyone has followed this tutorial with Laravel 5 I would be grateful for any info on this part: Outputting XML with PHP.


Answers:


There is no way to use Blade templating within an external Javascript file.

Laravel can only pass data to a view/template; Javascript files are loaded externally and therefore App data is not passed to them.

In order to get around this, you need to create <script> tags within your Blade template file:

{{-- Code in your template file, e.g., view.blade.php --}}

<script type="text/javascript">

// Put all locations into array
var locations = [
@foreach ($articles as $article)
    [ "{{ $article->lat }}", "{{ $article->lng }}" ], 
@endforeach
];

// NOTE: I've added a comma which will be needed to delimit each array within the array.
//       Quotes will also be needed since lat and long are not integers.

</script>

Make sure that this snippet comes before the code for including your maps.js file. If you've inlcuded the maps.js file within your <head> tags, you're going to need to move that inclusion snippet down to the bottom of the page.

This is a rather rudimentary solution, however. A better way would be to use AJAX to retrieve the data from within your maps.js file upon initialization.

This would, of course, require you to create a new Controller method and corresponding route that can handle the request and return the required data.