2015-11-03 50 views
7

我正在尝试使用此tutorial和Laravel 5制作商店定位器应用程序。这些问题中的人HereHere似乎是使用@foreach循环和其他刀片模板语言来运行其经纬度坐标。他们如何做到这一点?如何在脚本文件中使用Laravel Blade?

我基本上不知道如何通过坐标使用刀片循环,当我的地图代码是在一个js文件?这怎么可能?我在做一些完全错误的事情吗?

我显示我的地图,包含js文件(maps.js)具有以下代码:

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 

} 

但很明显的是卡上的@foreach线。如果有人按照Laravel 5的教程进行操作,我将非常感激这方面的任何信息:使用PHP输出XML。

回答

15

无法在外部JavaScript文件中使用Blade模板。

Laravel只能将数据传递给视图/模板; Javascript文件是从外部加载的,因此App数据不会传递给它们。

为了解决这个问题,您需要在刀片服务器的模板文件中创建<script>标签:

{{-- 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> 

确保此片段来为包括您maps.js文件代码。如果您在<head>标签中包含maps.js文件,则需要将该包含片段移动到页面底部。

然而,这是一个相当基本的解决方案。更好的方法是在初始化时使用AJAX从maps.js文件中检索数据。

这当然会要求您创建一个新的Controller方法和相应的路由,以处理请求并返回所需的数据。

+0

这对我来说非常适合!但是,有没有办法用多个变量来做到这一点?例如,如果我想将内容放入每个标记中。我怎么能这样做? – AlmostPitt

+0

你是什么意思? ('myView',['variable1'=> $ variable1,'variable2'=> $ variable2,etc ...]);'; – heisian

+0

是的,我想将单独的数组放在变量位置中。例如,对于每个位置,我还想注入位置的标题和一些其他信息。看到这篇文章后,我在这方面发布了另一个问题。也许这将有助于澄清我的问题:https://stackoverflow.com/questions/45924237/laravel-5-4-blade-javascript-google-maps-insert-foreach-with-multiple-variabl – AlmostPitt

1

您可以创建一个从Eloquent对象JavaScript对象,例如看看下面的代码:

// index.blade.php 
<script>var userObj = {{ $authUser or 'undefined' }}</script> 

这是一个blade看法,我只是加载view并传递到collection鉴于使用的东西像这样(使用view composer):

View::composer('layouts.master', function($view) { 
    $user = null; 
    if(Auth::check()) { 
     $user = Auth::user(); 
    } 
    $view->with('authUser', $user); 
}); 

所以,在我view我已经$authUser所以CA ñ它转换为JS对象容易,如:

<script>var userObj = {{ $authUser or 'undefined' }}</script> 

所以,现在,我可以把它作为一个JS对象,它是在userObj变量(JavaScript的)。检查this article of mine,这是我近一年前为Laravel-4写的。

1

在您提供的示例中,他们使用的是刀片,因为它们位于刀片文件中,并且所有JavaScript位于标记之间。它不是.js文件类型,因此您可以通过这种方式使用刀片语言功能。