Laravel Blade Template Engine
Laravel provide simple and very powerful templating system. This templating engine combines one or more templates which is driven by inheritance and section to produce resulting views. Blade have its own controlling structure such as loops and conditional statements.Inheritance and Section are two primary benefits of using Blade template engine.To create Blade template, simply create your view file with the extension .blade.php
instead of .php
and it is typically stored in the resources/views directory.
- <!-- Stored in resources/views/layouts/default.blade.php -->
- <html>
- <head>
- <title>Application Name - @yield('title')</title>
- </head>
- <body>
- @section('sidebar')
- This is the default sidebar.
- @show
- <div class="container">
- @yield('content')
- </div>
- </body>
- </html>
As you can notice that file contains HTML tags follow with some blade sytax which is known as @section
and @yield
.The @section directive define a section of content while the @yield define the content area, In this section conent of pages will display.
Now let's create a child page which inherits this default or master layout.
Extending or Inheriting a LayoutTo inherit master layout in child pages, you will have to use @extends
directive.You can also inject content in your section from child page by using @section
directive.
- <!-- Stored in resources/views/child.blade.php -->
- @extends('layouts.default')
- @section('title', 'Page Title')
- @section('sidebar')
- <p>This is appended to the default sidebar.</p>
- @endsection
- @section('content')
- <p>Define body content area.</p>
- @endsection
You can display your data by using `curly` braces. For example :
Welcome {{ $name }}
Checking data if exist
If you don't know variable is set or not then you use ternary operator in PHP, in same way you will use in Laravel.
{{ isset($name) ? $name : 'Default text' }}
Instead of writing a ternary statement, Blade provide a short-cut
{{ $name or 'Default text' }}Control Structures
Blade provide short-cuts for common PHP control structures.
IF StatementsYou will use if-else statements through @if
@elseif
@else
@endif
directives.
- @if (count($data) === 1)
- I have one data!
- @elseif (count($data) > 1)
- I have multiple data!
- @else
- I don't have any data!
- @endif
- @for ($i = 0; $i < 10; $i++)
- The current value is {{ $i }}
- @endfor
- @foreach ($results as $result)
- <p>This is result of {{ $result->id }}</p>
- @endforeach
- @while (true)
- <p>I'm looping forever.</p>
- @endwhile
Blade provide @include
directive that allow you to include file easily.
- <div>
- <form>
- @include('foldername.filename')
- </form>
- </div>