Laravel Blade Reference

Here are some of the Laravel Blade snippets that we use when we code our views- 

1. To output a variable on blade template:-

{{}}

Laravel by default escapes the data before display:-

eg: 
{{ '<script>alert("spam spam spam!")</script>'}}
will appear as plain text because it escapes.

However to output an un-escaped data on view, use below method:-

{!! '<script>alert("spam spam spam!")</script>' !!} will run this js alert on window.

Blade comments:-

{{-- Output the $name variable. --}}

Determining variable existence:-

{{ $school or 'Don Bosco' }}

Looping over an array:-

 
@foreach($mylist as $list)
  <ul>
      <li>{{$list}}</li>
  </ul>
@endforeach 
 
@for ($i = 0; $i &lt; 10; $i++) 
    The current value is {{ $i }} 
@endfor 
 
@while (true)
   Iam looping forever.
@endwhile

If conditional:-

@if (condition)
@endif
 
@if (condition)
@else
@endif
 
@if (condition)
@elseif(condition)
@else
@endif

Helper functions:-
To provide URL on views:-

 url('/articles', $articles->id)

Service Injection:-

1
2
@inject('metrics', 'App\Services\MetricsService')
Monthly Revenue: {{ $metrics-&gt;monthlyRevenue() }}.

Layout:-

To create a layout, first create a directory within resources/views called layouts
Then-

 @yield('content')

The @yield directive identifies the name of the section that should be embedded into the template.

Then open view template, if the layout file is master.blade.php-

@extends('layouts.master')

The @extends directive tells Laravel which layout should be used

  @section('content')
  @endsection

Defining Multiple Layout Sections:-
On layout file:-

<div class="container">
 <div class="col-md-9">@yield('content')</div>
  <div class="col-md-3">
   @section('advertisement')This is an advertisement!
   @show
  </div>
</div>

@show directive means- close that section and yield it immediately else you need to explicitly define like below-

    @endsection
    @yield('advertisement')

On view blade templates, you can reference these sections as well, like below

  @section('advertisement')
    @parent
    Here goes the advt. contents.....
  @endsection

This will prepends the layout data appear in that section with view data appear in that section.
if we don’t add @parent then layout date appear in advertisement section will be eliminated and view section data will only appear.

Including View Partials:-

  @include('view.name')

All variables that are available to the parent view will be made available to the included view

You can also pass an array of extra data to the included view like

   @include('view.name', ['var'=>'data'])
 
   @foreach ($links as $link)
      @include('partials.row', array('link' => $link))
   @endforeach

That’s all for now. Happy coding.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.