Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 327
Cedric Avatar asked Aug 19 '15 17:08

Cedric


People also ask

Can I use blade template without Laravel?

You could download the class and start using it, or you could install via composer. It's 100% compatible without the Laravel's own features (extensions).

What is a blade template?

The Blade is a powerful templating engine in a Laravel framework. The blade allows to use the templating engine easily, and it makes the syntax writing very simple. The blade templating engine provides its own structure such as conditional statements and loops.

What is it blade template engine package?

Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.


3 Answers

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

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

like image 149
BARNZ Avatar answered Oct 17 '22 01:10

BARNZ


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

like image 34
yangqi Avatar answered Oct 17 '22 03:10

yangqi


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.

like image 2
jberculo Avatar answered Oct 17 '22 01:10

jberculo