Sunday, 5 November 2017

Laravel new Features in Blade If Directives

A new Blade addition in Laravel 5.5 will add support for simplifying custom ifstatements in your views.
The syntax might something like this in your AppServiceProvider::boot()method:
use Illuminate\Support\Facades\Blade;

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->isAdmin();
});
The new Blade::if() makes it convenient to abstract repetitive checks out of templates, making them more readable:
@admin
    <a href="{{ route('super.secret') }}">Secret Page</a>
@else
    Welcome Guest. <a href="{{ route('login') }}">Login</a>
@endadmin
In previous versions of Laravel, you would have to write a bit more code. For example, David Hemphill tweeted some really cool directives using this technique in Laravel 5.4:
//AppServiceProvide
Blade::directive('prod',function($beta){
 return "<?php if(app()->environment('production')):?>";
});
Blade::directive('endprod',function($beta){
 return "<?php endif; ?>";
});

-----------------------------------
//In your blade template
@prod
<script src="some-production-only-script" async></script>
@endprod
Which is now simplified even more in Laravel 5.5:
Blade::if('prod', function () {
    return app()->environment('production');
});
You can also pass arguments to make the checks more dynamic:
Blade::if('env', function ($env) {
    return app()->environment($env);
});
Which would then look like this in your templates:
@env('production')
  <script src="some-prod.js"></script>
@endenv
If you want to learn more about Blade::if(), Laracasts has a video tutorial on it, and we look forward to seeing what you’ll come up with!

No comments:

Post a Comment

cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in Laravel

  WampServer: Download this file:  http://curl.haxx.se/ca/cacert.pem Place this file in the  C:\wamp64\bin\php\php7.1.9  folder Open  php.in...

Popular Articles