Laravel blade is powerful template engine which makes short tags directive and easy to reuse templates. Most of the templates restrict to use other language but blade gives more flexibility and we can use PHP as well in template. Directives start with prefix @
and accepts parameter. In this article i will take a simple example to demonstrate the Laravel blade directive.
To create the custom directive Laravel provides Blade::directive
method which accepts two parameters, one is name of directive and second callback function when its called from view.
Let’s begin with simple steps:
Step 1: Create a laravel project
First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations
composer create-project laravel/laravel example-app
Step 2: Register Directive in AppServiceProvider
Next step is to register the directive in AppServiceProvider
, In Laravel service providers are central place for bootstrapping any component, module, directive or itself Laravel. therefore, let’s register our directive in AppServiceProvider
. In this example i will create a simple directive to show the long text in trimmed text format with dot.
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Blade::directive('ellipsis', function ($expression) {
return "<?php strlen($expression)>100?substr($expression,0,100).'...':$expression; ?>";
});
}
}
Step 3: Create a view
Now, create a view in resources/views folder to check our implementation
<div class="row">
Long : {{$longText}} <br><br>
Trimmed Text : @ellipsis($longText)
</div>
<!-- credits -->
<div class="text-center">
<p>
<a href="#" target="_top">Laravel 8 custom directive </a>
</p>
<p>
<a href="https://readerstacks.com" target="_top">readerstacks.com</a>
</p>
</div>
Step 4: Create route to check implementation
Create a simple route and call the view
<?php
use Illuminate\Support\Facades\Route;
Route::get('/check-directive',function(){
return view("custom_directive",['longText'=>'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum']);
});
Screenshot: