Cedric
Cedric

Reputation: 5303

How to include a blade template only if it exists?

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

@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.

What would be great is something like that :

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

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

Upvotes: 20

Views: 27980

Answers (5)

jberculo
jberculo

Reputation: 1113

Late to the show, but there's another quite handy template function:

Often you'd like to include a template when it is present, or include some other template if not. This could result in quite ugly if-then constructs, even when you use '@includeIf'. You can alse do this:

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

This will include - as the function name suggests - the first template found.

Upvotes: 3

yaroslawww
yaroslawww

Reputation: 1088

Laravel >= 7, there directive includeIf

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

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

Upvotes: 1

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:

use Illuminate\Support\Facades\View;

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

Upvotes: 3

yangqi
yangqi

Reputation: 683

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

@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

Upvotes: 32

BARNZ
BARNZ

Reputation: 1329

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

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

Upvotes: 44

Related Questions