How to include a blade template only if it exists?

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


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

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


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')) {
    \\
}

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.

Tags:

Laravel

Blade