如何仅在存在 blade 模板时包含它?

How to include a blade template only if it exists?

如何@include blade 模板 如果它存在? 我可以做类似的事情 :

@if (File::exists('great/path/to/blade/template.blade.php'))
   @include('path.to.blade.template')
@endif

但这确实不够优雅和高效。

我可以在没有 if 语句的情况下包含它,如果文件不在此处,则捕获并隐藏错误,但这有点脏,如果不是野蛮的话。

如果是那样的东西就好了:

@includeifexists('path.to.blade.template')

(伪代码,但是这个blade命令不存在)

您可以使用 View::exists() 检查视图是否存在。

@if(View::exists('path.to.view'))
    @include('path.to.view')
@endif

或者您可以扩展 blade 并添加新指令

Blade::directive('includeIfExists', function($view) {

});

在这里查看官方文档:http://laravel.com/docs/5.1/blade#extending-blade

有类似的问题。原来有一个 @includeIf blade 指令用于此目的。

只需@includeIf('path.to.blade.template')

控制器中需要时 (from this documentation):

确定视图是否存在如果您需要确定视图是否存在 存在,你可以在调用视图助手后使用 exists 方法 没有争论。如果视图存在于 磁盘:

use Illuminate\Support\Facades\View;

if (View::exists('emails.customer')) {
    \
}

Laravel>=7,有指令includeIf

@includeIf('view.name', ['some' => 'data'])

https://laravel.com/docs/7.x/blade#including-subviews

迟到了,但还有另一个非常方便的模板函数:

通常您希望在模板存在时包含它,如果模板不存在则包含其他模板。这可能会导致非常丑陋的 if-then 构造,即使您使用“@includeIf”也是如此。您也可以这样做:

@includeFirst([$variableTemplateName, "default"]);

这将包括 - 如函数名称所示 - 找到的第一个模板。