Creating Laravel Blade Custom Directives

As you know Blade is template engine of Laravel and with it's own special syntax, it is helps us to write more readable codes without writing php directly in views and the names of the commands that we use in our view folders which starts with the @ sign, we call them directive.

In this article I am going to show you how you can identify a special directive.

In its simplest form, you can identify a directive in this way;

Blade::directive('directiveName', function($expression){
    return $expression;
});

Either identify this directive in your controller file and use just there which is not logical or identify in boot() method which is under the AppServiceProvider and use it any where.

If you are going to use in controller file firstly add this to head of your file.

use Illuminate\Support\Facades\Blade;

Later you may identify in the method in this way;

..

public function index()
{

    ..

    Blade::directive('text', function($express){
        return $express;
    });

    ..
}

..

And when you use it as @text(hello world) in the view, it is just printed to screen. Yes, this directive does not work: D Because you have to write more meaningful directives.

Now let's identify some directive as global. We identify this in boot() method in app/Providers/AppServiceProvider.php file.

<?php

use IlluminateSupportFacadesBlade;
    
class AppServiceProvider extends ServiceProvider
{
    ..
    public function boot()
    {
        Blade::directive('style', function($expression){
            if (!empty($expression)) return '<link rel="stylesheet" type="text/css" href="' . mix('css/' . $expression) . '">';
            return '<style>';
        });

        Blade::directive('endstyle', function(){
            return '</style>';
        });

        Blade::directive('page', function($expression){
            return "<?php if (request()->routeId('{$expression}')){ ?>";
        });

        Blade::directive('endpage', function(){
            return "<?php } ?>";
        });
    }
    ..

And now we can use  in our view pages in this way;

@page(profile)
    //profile
@endpage

@style
body {
    background-color: red;
}
@endstyle

@style(users.css)

Finally, if you want, there is a using is also available Blade::if() in this way;

Blade::if('home', function(){
    return request()->routeIs('index');
});

When you define as @home @else and @endhome directives can be used automatically. So;

@home
    //it's home
@else
    //else
@endhome

 

Comments

There are no comments, make the firs comment