一般咱们在视图模板中编写复杂的逻辑,看上去显得很杂乱,那么使用自定义的模板Directives,能够简化你的视图逻辑,编写出更优雅的代码,Laravel Blade是一种将其特殊语法编译成PHP和HTML的模板引擎。其特殊语法指令,指令是加糖功能,在其后隐藏杂乱的代码。模板包含大量的内置指令,例如@foreach/@if/@section/@extends等等,内置的指令对于作一个简单的项目足以,可是当你在代码中编写重复复杂的功能时,那么自定义模板指令或许能够帮你优化你的视图结构。php
$expression参数是可选的html
\Blade::directive('directive_name', function ($expression) { return $expression; });
视图中用法Demoexpress
<p>@hello('World')</p>
声明自定义模板指令的位置AppServiceProvider.php
缓存
<?php namespace App\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Blade::directive('hello', function ($expression) { return "<?php echo 'Hello ' . {$expression}; ?>"; }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }
以这种方式定义的指令加载成功,能够在任何模板中使用ide
不能直接访问自定义指令中传递的多个参数,须要将其遍历出来函数
<p>@greet('Hi', 'Hammad')</p> \Blade::directive('hello', function ($expression) { list($greet, $name) = explode(', ', $expression); return "<?php echo {$greet} . ' ' . {$name}; ?>"; });
像 array() list() 这种并非一个函数,而是一种语言结构post
必定要时刻记住须要过滤输出,通常使用{{}}时候,Blade已经预先执行了过滤操做,为了不恶意用户将js代码注入到站点,必定要转义HTML,能够使用Laravel自带的函数e(),也至关于htmlentities()优化
\Blade::directive('hello', function ($expression) { return "<?php echo 'Hello ' . e({$expression}); ?>"; });
每次添加或修改自定义模板指令以后,必定要先清除缓存视图模板,能够使用clear Artisanspa
php artisan view:clear
在使用自定义的模板指令的时候,大多数只是某种形式的条件,这些要求咱们须要注册三个独立指令,if/else/endif,目前Laravel5.5已经支持简化条件指令,例以下面的实例,模板能够使用admin/else/endadmincode
public function boot() { \Blade::if('admin', function () { return auth()->check() && auth()->user()->isAdmin(); }); }
2017 ending! script maker!