101. 在 Blade 模板中使用过滤器 Filters—— thepinecode/blade-filters
在 Blade 模板中使用过滤器 Filters —— thepinecode/blade-filters
也许你使用过其他语言的模板引擎,会有过滤器这样的功能,那在 Laravel 的 Blade 中想要使用类似的功能,可以使用今天的这个扩展包 github.com/thepinecode/blade-filte... 。
安装
$ composer require thepinecode/blade-filters
安装上之后不需要任何配置就可以工作了
使用
不使用扩展包
resources/views/welcome.blade.php
<div class="title m-b-md">
Laravel
</div>
<h1>
{{ Str::limit(Str::title('this is a title'), 10)}}
</h1>
使用扩展包
resources/views/welcome.blade.php
<div class="title m-b-md">
Laravel
</div>
<h1>
{{ Str::limit(Str::title('this is a title'), 10)}}
</h1>
<h1>
{{ 'this is a title' | title | limit:10 }}
</h1>
可以同时使用多个过滤条件。
位运算
使用的分隔符是 |
,这样就与位运算的操作符冲突了,所以当我们在 Blade 模板中使用位运算时,需要放在括号里面。
例如字幕 a (01100001) 按位或 b (01100010)结果是 c(01100011),测试一下。
resources/views/welcome.blade.php
<h1>
{{ ('a' | 'b') | upper }}
</h1>
自定义 Filter
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Pine\BladeFilters\BladeFilters;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
BladeFilters::macro('combine', function ($value, $one, $two) {
return $value.' '.$one.' '.$two;
});
}
.
.
.
resources/views/welcome.blade.php
<h1>
{{ 'test' | combine:'one','two' }}
</h1>