101. 在 Blade 模板中使用过滤器 Filters—— thepinecode/blade-filters

在 Blade 模板中使用过滤器 Filters —— thepinecode/blade-filters

也许你使用过其他语言的模板引擎,会有过滤器这样的功能,那在 Laravel 的 Blade 中想要使用类似的功能,可以使用今天的这个扩展包 github.com/thepinecode/blade-filte...

安装

$ composer require thepinecode/blade-filters

在 Blade 模板中使用过滤器 Filters —— 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>

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
发起讨论 只看当前版本


暂无话题~