Templates

Blade is a simple, yet powerful templating engine provided with Laravel. Unlike controller layouts, Blade is driven by template inheritance and sections. All Blade templates should use the extension.

Defining A Blade Layout

Using A Blade Layout

  1. @extends('layouts.master')
  2. @section('title', 'Page Title')
  3. @section('sidebar')
  4. @parent
  5. <p>This is appended to the master sidebar.</p>
  6. @section('content')
  7. <p>This is my body content.</p>
  8. @stop

Note that views which extend a Blade layout simply override sections from the layout. Content of the layout can be included in a child view using the @parent directive in a section, allowing you to append to the contents of a layout section such as a sidebar or footer.

Sometimes, such as when you are not sure if a section has been defined, you may wish to pass a default value to the @yield directive. You may pass the default value as the second argument:

  1. @yield('section', 'Default Content')

Other Blade Control Structures

Echoing Data

  1. Hello, {{ $name }}.
  2. The current UNIX timestamp is {{ time() }}.

Echoing Data After Checking For Existence

Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. Basically, you want to do this:

However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut:

Displaying Raw Text With Curly Braces

If you need to display a string that is wrapped in curly braces, you may escape the Blade behavior by prefixing your text with an @ symbol:

  1. @{{ This will not be processed by Blade }}
  1. Hello, {!! $name !!}.

If Statements

  1. @if (count($records) === 1)
  2. I have one record!
  3. @elseif (count($records) > 1)
  4. I have multiple records!
  5. @else
  6. I don't have any records!
  7. @endif
  8. @unless (Auth::check())
  9. You are not signed in.
  10. @endunless

Loops

  1. @for ($i = 0; $i < 10; $i++)
  2. @endfor
  3. @foreach ($users as $user)
  4. <p>This is user {{ $user->id }}</p>
  5. @forelse($users as $user)
  6. <li>{{ $user->name }}</li>
  7. @empty
  8. <p>No users</p>
  9. @endforelse
  10. @while (true)
  11. <p>I'm looping forever.</p>
  12. @endwhile

Including Sub-Views

You may also pass an array of data to the included view:

  1. @include('view.name', ['some' => 'data'])

Overwriting Sections

To overwrite a section entirely, you may use the overwrite statement:

  1. @extends('list.item.container')
  2. @section('list.item.content')
  3. <p>This is an item of type {{ $item->type }}</p>
  4. @overwrite

Displaying Language Lines

  1. @lang('language.line')

Comments