先创建一个练习的路由文件 view.php
1. 基本操作
视图包含应用程序的 HTML,并且将控制器 / 应用程序逻辑与演示逻辑分开。视图文件存放于 resources/views 目录下。我们可以通过路由定向到视图,也可以路由→控制器→视图。我想这仅仅是取决于你的业务是否需要这么去做,或者说是否业务逻辑使有必须分层的必要性。
1.1 最简单的视图使用方式
首页面的路由视图实现
<?php# 首页面路由试图,省略了文件全名称,welcome.blade.phpRoute::view('index', 'welcome');
1.2 使用目录结构视图
我先在 resources\views\myView\see.blade.php 中定义一个自己的视图文件,代码如下:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><h3>我是 resources\views\myView\see.blade.php</h3></body></html>
路由
<?php# mu 目录 视图文件Route::view('see', 'myView/see');
1.3 传递数组数据
修改一下 resources\views\myView\see.blade.php 中定义的代码,注意模板的使用
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><h3>我是 resources\views\myView\see.blade.php</h3><h4>{{ $name }}</h4><h4>{{ $age }}</h4><h4>{{ $hobby }}</h4></body></html>
路由文件
<?php# 传递参数Route::get('see', function () {# 这里我是用'myView.see' 貌似也没有啥区别 @……@return view('myView/see', ['name' => '向上', 'age' => 24, 'hobby' => 'cook']);});# 下面的这种使用方式也是可以的Route::get('see', function () {return View::make('myView/see', ['name' => '向上', 'age' => 24, 'hobby' => 'cook']);});
1.4 使用with()传递数据
这是一种相对于上一种更加灵活的方式,路由如下:
<?php# 传递参数的另外一种使用方式 withRoute::get('list', function () {$list = ['name' => '向上', 'age' => 24, 'hobby' => 'cook'];return view('myView/list')->with('list', $list);});
模板文件
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><h3>我是 resources\views\myView\list.blade.php</h3><h3>{{ $list['name'] }}</h3><h3>{{ $list['age'] }}</h3><h3>{{ $list['hobby'] }}</h3></body></html>
1.5 判断视图是否存在
路由,创建一个404页面,rain这个对应的视图页面是没有创建的
<?phpuse Illuminate\Support\Facades\View;# 判断视图是否存在Route::get('rain', function () {if (View::exists('myView.rain')) {//}return view('myView.404');});
404.blade.php
... ...
测试
