laravel 如何仅在刀片模板存在时才包含它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32102272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:13:20  来源:igfitidea点击:

How to include a blade template only if it exists?

laravelblade

提问by Cedric

How to @include a blade template onlyif it exists ? I could do something like that :

当刀片模板存在时,如何@include 刀片模板?我可以做这样的事情:

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

But that really isn't elegant and efficient.

但这确实不优雅和高效。

I could include it without if statements, and catch & hide errors if the file isn't here, but that is a little dirty, if not barbaric.

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

What would be great is something like that :

什么会很棒是这样的:

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

(pseudo code, but this blade command does not exist)

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

回答by BARNZ

Had a similar issue. Turns out there is an @includeIfblade directive for this purpose.

有一个类似的问题。事实证明@includeIf,为此目的有一个刀片指令。

Simply do @includeIf('path.to.blade.template')

简单地做 @includeIf('path.to.blade.template')

回答by yangqi

You can use View::exists()to check if a view exists or not.

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

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

Or you can extend blade and add new directive

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

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

});

Check out the official document here: http://laravel.com/docs/5.1/blade#extending-blade

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

回答by user2075039

When needed in a Controller (from this documentation):

在控制器中需要时(来自本文档):

Determining If A View Exists If you need to determine if a view exists, you may use the exists method after calling the view helper with no arguments. This method will return true if the view exists on disk:

确定一个视图是否存在如果你需要确定一个视图是否存在,你可以在调用不带参数的视图助手后使用exists方法。如果视图存在于磁盘上,此方法将返回 true:

use Illuminate\Support\Facades\View;

use Illuminate\Support\Facades\View;

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