Home > Backend Development > PHP Tutorial > Laravel向视图传递变量

Laravel向视图传递变量

WBOY
Release: 2016-06-23 13:06:39
Original
1121 people have browsed it

传递变量

->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变量。这样的话,视图就能够获取到值,然后显示。    }}
Copy after login

app/resources/views/welcome.blade.php

        <div class="container">            <div class="content">                <div class="title">Laravel 5</div>                {{$name}} //这里就是视图中的name变量            </div>        </div>
Copy after login

传递数组

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

app/Http/Controllers/SiteController.php

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

app/resources/views/welcome.blade.php

        <div class="container">            <div class="content">                <div class="title">Laravel 5</div>                {{$first-key}}{{$last-key}}            </div>        </div>
Copy after login
Copy after login

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

app/Http/Controllers/SiteController.php

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

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

app/resources/views/welcome.blade.php        <div class="container">            <div class="content">                <div class="title">Laravel 5</div>                {{$first}}{{$last}}            </div>        </div>
Copy after login

或者通过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里。    }}
Copy after login

app/resources/views/welcome.blade.php

        <div class="container">            <div class="content">                <div class="title">Laravel 5</div>                {{$first-key}}{{$last-key}}            </div>        </div>
Copy after login
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template