Blade 模版扩展应用一例:为低版 Laravel 添加 csrf 及 method 指令
5.8版本里面有两个很好用的指令,他们是@csrf
以及@method(...)
。对于老版本怎么办?如果也想用这两个指令的话,那就需要扩展Blade模版了。方法很简单,只需要在app\Providers\AppServiceProvider.php
文件的boot()方法里面加几行代码就可以了。
public function boot()
{
Blade::directive('csrf', function (){
return '<?php echo csrf_field(); ?>';
});
Blade::directive('method', function ($method){
// 指令不带参数则默认是 delete 方法
$method= $method ?: "'delete'";
return "<?php echo method_field($method); ?>";
});
...
}
如此一来就可以在模版里面使用这两个指令了(先要敲入命令php artisan view:clear
清掉缓存),比如下面的删除按钮
<a href="javascript:" data-method="delete">
<i class="fa fa-trash-o"></i> 删除
<form action="http..." method="post" class="d-none">
@csrf @method
</form>
</a>
最终生成的html代码如截图
JS代码如下,先弹出温馨警告询问是否真要删除,如果真删就使用delete方法提交表单。
$('a[data-method=delete]').click(function () {
swal({
title: '确定要删除吗?',
icon: 'warning',
dangerMode: true,
buttons: ['取消', '确定'],
})
.then(yes=>{
if(yes)
$(this).children('form').submit();
})
})
本作品采用《CC 协议》,转载必须注明作者和本文链接