【问题标题】:how to exclude certain views with laravel view composer如何使用 laravel 视图作曲家排除某些视图
【发布时间】:2016-11-29 11:26:52
【问题描述】:
如何确保通过视图编辑器为选定视图加载数据,并且只排除少数、两个要具体的视图?我可以使用正则表达式而不是“*”吗?
public function boot()
{
view()->composer(
'*',
'App\Http\ViewComposers\ProfileComposer'
);
}
我只想避免两个视图,它们扩展了其他人使用的相同刀片,不确定声明所有其他 99 个刀片是否是最好的 - 如果我可以定义那些要被排除在外的刀片很棒。
【问题讨论】:
标签:
php
laravel
laravel-5.2
laravel-routing
【解决方案1】:
也许这不是最好的方法,但它可以这样做
在您的服务提供商中注册您的视图作曲家
public function boot()
{
view()->composer(
'*',
'App\Http\ViewComposers\ProfileComposer'
);
}
在您的ProfileComposer compose 方法中查看类存储库是类型提示的。使用它来获取当前视图名称的名称,并为排除的视图名称设置条件。
class ProfileComposer
{
public function __construct()
{
// Dependencies automatically resolved by service container...
}
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$excludedViews = ['firstView','SecondView'];
//Check if current view is not in excludedViews array
if(!in_array($view->getName() , $excludedViews))
{
$view->with('dataName', $this->data);
}
}
}