Home > Backend Development > PHP Tutorial > [Intermediate Laravel] 12-How-to-Write-Custom-Blade-Directives

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

WBOY
Release: 2016-06-23 13:06:19
Original
1069 people have browsed it

常用 Blade 语法

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

定制个性 Blade

修改 welcome.blade.php 页面:

<!DOCTYPEhtml><html>    <head>        <title>Laravel</title>    </head>    <body>        @hello    </body></html> 
Copy after login

修改 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()  {    //  }} 
Copy after login

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

修改 AppServiceProvider.php 中代码如下:

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

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

Blade 中参数处理

修改 welcome.blade.php 页面:

<!DOCTYPEhtml><html>    <head>        <title>Laravel</title>    </head>    <body>        @hello('world')    </body></html> 
Copy after login

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

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

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

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

Blade 中 对象传递

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

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

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

<!DOCTYPEhtml><html>    <head>        <title>Laravel</title>    </head>    <body>        @ago($user)    </body></html> 
Copy after login

修改 AppServiceProvider.php ,处理 $user :

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

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

Blade 中 with 辅助函数

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

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

访问效果如下图:

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template