Designinglives

June 23, 2017 at 5:25 pm

Laravel Blade templates

If you have never worked with a templating engine it’s about time you open the door to let a breeze run through your projects! I’m sure you will be amazed about how easy Blade will be to use as well as how clean your templates will look. Sharpen your Blades, here we go!

This is what my controller function would look like, it’s called from the routes file and will make sure our application has maximum flexibility.

public function view() {
    $data['title'] = 'Titel pagina';
    $data['subtitle'] = 'Subtitel pagina';
    $data['random'] = rand(1,3);
    $data['loop'] = ['<em>Item 1</em>', '<i>Item 2</i>', '<b>Item 3</b>'];
    $data['users'] = [];
		
    return view('pages.example', $data);
}

To use blade inside a template it’s necessary to make sure the name looks like this: example.blade.php. Laravel can automatically detect it needs to fetch the blade data and you won’t need to add the .blade when calling the view file from the controller.

Also notice the $data array we have build and passed through to the view.

Include templates

@include('view.name')
@include('pages.view', array('some'=>'data'))

Foreach (escaped) & comment tag:

{{-- Foreach --}}
<ul>
    @foreach($loop as $item)
        <li>{{ $item }}</li>
    @endforeach
</ul>

Foreach (non-escaped):
HTML tags will therefor be used as html tags, not as text.

{{-- Foreach non escaped --}}
<ul>
    @foreach($loop as $item)
        <li>{!! $item !!}</li>
    @endforeach
</ul>

PHP Date or random variable echo:

{{-- PHP Date --}}
<h1>{{ $title }}</h1>
<p>{{ date('d-m-Y') }}</p>

If, elseif:

{{-- If, else, ... --}}
@if ($random == 3)
    <p>3</p>
@elseif ($random == 2)
    <p>2</p>
@else
    <p>1</p>
@endif

Unless:
Notice, this isn’t something we can use inside PHP, though it might become very useful when using more complex structures.

@unless (Auth::check())
    <p>You are not signed in.</p>
@endunless

Forelse loop:
Another thing which in PHP doesn’t exist in this form but this can be very useful when dealing with arrays which can be empty.

{{-- Forelse loop, same as foreach --}}
<ul>
    @forelse($users as $user)
        <li>{{ $user->name }}</li>
    @empty
        <li>No users</li>
    @endforelse
</ul>

Now that we have had this all, what if we would like to use {{ }} inside our templates, for whatever reason you can think of? Blade also has a tag to use that as well, just add a @ sign in front of it to let Blade know it should ignore the tags here.

@{{ This will not be processed by Blade }}

Now that you we have let the breeze in it’s time to take another look at the templates you have made before and rewrite them to get proper more readable code!

0 likes blade , laravel 5 , templates
Share: / / /