[IntermediateLaravel] 12-How-to-Write-Custom-Blade-Directives Blade syntax
On the Blade template page, we often use the @ section command to define a content block and use the @ yield command to display the content of the specified block. we will discuss how to write a customized Blade command in the future.
Customized Blade
Modify the welcome. blade. php page:
Laravel @hello
Modify AppServiceProvider. php and add the custom hello command:
Class AppServiceProvider extends ServiceProvider {/*** Bootstrap any application services. ** @ return void */public function boot () {// add hello blade Blade: directive ('hello', function () {return 'Hello word';});}/*** Register any application services. ** @ return void */public function register (){//}}
At this time, we visit the home page to see the following results:
The code for modifying AppServiceProvider. php is as follows:
Public function boot () {// add hello blade Blade: directive ('hello', function () {// return 'Hello word1 '; return'
';});}
The access results remain unchanged because Laravel's page cache. Run php artisan view: clear to clear the cache and then access it again. The effect is as follows:
Blade parameter processing
Modify the welcome. blade. php page:
Laravel @hello('world')
Modify the boot method in AppServiceProvider. php and accept the $ expression parameter:
Public function boot () {// add hello blade Blade: directive ('hello', function ($ expression) {return"
";});}
At this time, we visit the home page to see the following results:
The actual access path is the cache file under/storage/framework/views.
Object transfer in Blade
Modify the route. php page and pass the user variable:
Route::get('/', function(){ return view('welcome')->with('user', App\User::first());});
Modify the welcome. blade. php page and accept $ user:
Laravel @ago($user)
Modify AppServiceProvider. php to process $ user:
Public function boot () {// add hello blade Blade: directive ('ago ', function ($ expression) {dd ($ expression );});}
At this time, we visit the home page to see the following results:
With auxiliary functions in Blade
How can we display objects normally? here we use the with helper function:
Public function boot () {// add hello blade Blade: directive ('ago ', function ($ expression) {return"
Updated_at-> diffForHumans ();?> ";});}
The access effect is as follows: