## Laravel学习笔记汇总——视图模板
// 视图模板传值
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
//或:
//use Illuminate\Support\Facades\View;
//return View::make('greeting', ['name' => 'James']);
});
<!-- resources/views/greeting.blade.php -->
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
// 也可以使用with传值
return view('greeting')
->with('name', 'Victoria')
->with('occupation', 'Astronaut');
// 和compact传值
$a = 1;
$b = 2;
return view('greeting', compact('a','b'));
// 如果在resources/views/xxx/a.blade.php文件夹里的模板文件,需要这样引用(xxx中不能有点句号):
return view('xxx.a');
// 使用多个可能的视图模板,从而支持模板的自定义覆盖
use Illuminate\Support\Facades\View;
return View::first(['custom.admin', 'admin'], $data);
// 判断一个view视图模板是否存在
use Illuminate\Support\Facades\View;
if (View::exists('emails.customer')) {
//
}
// 在所有的模板中共享数据,需要在一个ServiceProvider类中添加代码
namespace App\Providers;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::share('key', 'value');
}
}
// View Composers 是指视图在渲染时要执行的回调函数或类方法。
// 如果视图在每次渲染都绑定一定的数据,则可以使用view composer把绑定逻辑放到一个独立的地方,
// 适用于在多个路由或控制器都返回同一个视图,并且都总是需要同一批数据时。
// 我们可以在service provider中注册一个view composer,比如新建一个
// App\Providers\ViewServiceProvider 专门处理(需要在config/app.php)中加上这个ViewServiceProvider名字):
namespace App\Providers;
use App\Http\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function boot()
{
// Using class based composers...
View::composer('profile', ProfileComposer::class);
// Using closure based composers...
View::composer('dashboard', function ($view) {
//
});
// 将一个composer附加到多个view
View::composer(
['profile', 'dashboard'],
ProfileComposer::class
);
// 将一个composer附加到任意的view
View::composer('*', function ($view) {
//
});
}
}
// 上面的代码需要有一个App\Http\View\Composers\ProfileComposer类,带上compose方法
namespace App\Http\View\Composers;
use App\Repositories\UserRepository;
use Illuminate\View\View;
class ProfileComposer
{
protected $users;
public function __construct(UserRepository $users)
{
// Dependencies are automatically resolved by the service container...
$this->users = $users;
}
public function compose(View $view)
{
$view->with('count', $this->users->count());
}
}
// View Creators 在视图实例化后马上执行(区别于View Composer是在渲染前执行)
use App\Http\View\Creators\ProfileCreator;
use Illuminate\Support\Facades\View;
View::creator('profile', ProfileCreator::class);
// Laravel 在编译后的view不存在,或者编译的view存在但是未编译的view有过修改时,就会重新编译
// 在项目部署时,可以使用命令将所有的view预编译
php artisan view:cache
// 使用下面的命令清除所有编译过的view
php artisan view:clear