Laravel向视图传递变量

原创
2016-06-23 13:06:39 749浏览

传递变量

->with方法app/Http/Controllers/SiteController.php

class SiteController extends Controller{    //    public function index(){        $first = 'first';        $last = 'last';        return view('welcome')->with('name',$first);        //这个name是视图中的变量名,这里with的意思是将controller的这个$first赋值到view视图中的name变量。这样的话,视图就能够获取到值,然后显示。    }}

app/resources/views/welcome.blade.php

        
Laravel 5
{{$name}} //这里就是视图中的name变量

传递数组

通过->with方法来传递数组

app/Http/Controllers/SiteController.php

class SiteController extends Controller{    //    public function index(){        return view('welcome')->with([            'first-key'=> 'first',            'last-key'=>'last'        ]);    }}

app/resources/views/welcome.blade.php

        
Laravel 5
{{$first-key}}{{$last-key}}

或者通过直接传递一个数组

app/Http/Controllers/SiteController.php

class SiteController extends Controller{    $data = [];    $data['first] = 'first';    $data['last'] = 'last';    public function index(){        return view('welcome',$data);    }}

不过这里虽然传入的是一个数组,但是使用的时候其实相当于直接使用数组的键作为了变量

app/resources/views/welcome.blade.php        
Laravel 5
{{$first}}{{$last}}

或者通过compact

class SiteController extends Controller{    public function index(){        $first-key = 'first';        $last-key        = 'last';        return view('welcome',compact('first-key','last-key'));        //compact是php的基本命令,创建一个包含变量名和它们的值的数组,创建数组后,将变量名转为数组的key来传递到view里。    }}

app/resources/views/welcome.blade.php

        
Laravel 5
{{$first-key}}{{$last-key}}

本文由 PeterYuan 创作,采用 署名-非商业性使用 2.5 中国大陆 进行许可。 转载、引用前需联系作者,并署名作者且注明文章出处。神一样的少年 » Laravel向视图传递变量

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。