Laravel 5.4 #5 : Going deeper into Blade

In this post, we will go deeper into Blade. We are going to create a layout and extend it from the different templates, also we are going to use includes to include from a view the errors and the post submission form. Also, we are going to use the conditionals of Blade to display a message if there aren’t any post.

Layout and extends

layout is a parent template that can contain a header, footer, etc. common for several views. This avoids the task of writing the same thing several times, only with writing it once and dynamizing what is not shared (title, menu active links, etc.).

Create a file in  resources/views that is called  layout.blade.php and it will contain this:

And now we extend it in our views (posts.blade.php and post.blade.php):

What it does is in the div with id container add the code that is in @section(‘content’).

 

Includes

Now, we are going to separate the form and the section of errors in separated views, to be able to reuse them without having to rewrite the same code.

We take the form code that is in  posts.blade.php  and we put it in a separated file:

Do the same with the errors:

In  posts.blade.php we should replace what we just copied in the new views for:

With all this, we are already including new views from separate ones. We could also reuse them in other views if necessary, simply with the @include.

 

Detect if there are posts

To detect if there are posts to show and if there aren’t, show a message, we are going to modify the foreach loop of  posts.blade.php  and use other tag called forelse.

There are other ways to do the same, for example with an if that counts how many posts there are and if there are 0 show the message and if there are more show the posts.

 

Blade is very extensive, if you want to look at more things about it, I leave here the link to the documentation.

 

In the next post, we will talk a little bit more in depth about Eloquent ORM.