热搜:NVER node 开发 php

[Intermediate Laravel] 12-How-to-Write-Custom-Blade-Directives

2024-07-20 17:30:01
[Intermediate Laravel] 12-How-to-Write-Custom-Blade-Directives

常用 Blade 语法

在 Blade 模版页面,我们常用 @section 命令定义一个内容区块,用 @yield 命令显示指定区块的内容等等,后续我们探讨如何写定制的 Blade命令。

定制个性 Blade

修改 welcome.blade.php 页面:

            Laravel                @hello     

修改 AppServiceProvider.php,新增自定义的 hello 指令:

class AppServiceProvider extends ServiceProvider{  /**   * Bootstrap any application services.   *   * @return void   */  public function boot()  {    // 新增 hello blade    Blade::directive('hello', function(){      return 'hello word';    });  }   /**   * Register any application services.   *   * @return void   */  public function register()  {    //  }} 

这时我们访问首页面效果如下图:

修改 AppServiceProvider.php 中代码如下:

  public function boot()  {    // 新增 hello blade    Blade::directive('hello', function(){//      return 'hello word1';      return '<?= "hello universe"; ?>';    });  } 

访问结果却并没有变化,这是因为 Laravel 的页面缓存。运行 php artisan view:clear 清理缓存后再次访问,效果如下图:

Blade 中参数处理

修改 welcome.blade.php 页面:

            Laravel                @hello('world')     

修改 AppServiceProvider.php 中 boot 方法,接受传入 $expression 参数:

  public function boot()  {    // 新增 hello blade    Blade::directive('hello', function($expression){      return "<?= 'hello '. $expression; ?>";    });  } 

这时我们访问首页面效果如下图:

实际访问路径为:/storage/framework/views/下的缓存文件。

Blade 中 对象传递

修改 route.php 页面,传递 user 变量:

Route::get('/', function(){  return view('welcome')->with('user', App\User::first());}); 

修改 welcome.blade.php 页面,接受 $user :

            Laravel                @ago($user)     

修改 AppServiceProvider.php ,处理 $user :

  public function boot()  {    // 新增 hello blade    Blade::directive('ago', function($expression){      dd($expression);    });  } 

这时我们访问首页面效果如下图:

Blade 中 with 辅助函数

如何让对象正常显示呢,这里我们借助 with 辅助函数:

  public function boot()  {    // 新增 hello blade    Blade::directive('ago', function($expression){      return "<?= with{$expression}->updated_at->diffForHumans(); ?>";     });  } 

访问效果如下图: