I have a custom function and I want to pass it in a blade template. Here is the function:

function trim_characters( $text, $length = 45, $append = '…' ) {

    $length = (int) $length;
    $text = trim( strip_tags( $text ) );

    if ( strlen( $text ) > $length ) {
        $text = substr( $text, 0, $length + 1 );
        $words = preg_split( "/[\s]| /", $text, -1, PREG_SPLIT_NO_EMPTY );
        preg_match( "/[\s]| /", $text, $lastchar, 0, $length );
        if ( empty( $lastchar ) )
            array_pop( $words );

        $text = implode( ' ', $words ) . $append;
    }

    return $text;
}

And the usage is like this:

$string = "A VERY VERY LONG TEXT";
trim_characters( $string );

是否可以将自定义函数传递给Blade 模板?谢谢.

推荐答案

你不需要pass个刀刃就可以了.如果您定义了您的函数,您可以在Blade 中使用它.


  1. 创建一个新的app/helpers.php文件.
  2. Add your trim_characters function to it.
  3. Add that file to your composer.json file.
  4. Run composer dump-autoload.

现在只需直接在blade中使用该功能:

{{ trim_characters($string) }}

Laravel相关问答推荐

laravel错误更新使用外键的数据库

Livewire 3软件包开发

Laravel phpunit 测试失败并出现 PDOException:SQLSTATE[HY000]:一般错误:1 接近0:语法错误

如何通过单击进入 vs 代码中的类

Mockery 和 Laravel 构造函数注入

laravel 基本路径

Laravel belongsToMany 关系在两个表上定义本地键

Laravel 5文件夹 struct 中的文件保存在哪里?

验证规则 required_if 与其他条件(Laravel 5.4)

.gitignore 不忽略文件夹

链接到容器时如何使用主机网络?

在 VSCode 上调试 Laravel 应用程序

如何在没有 Eloquent 的情况下创建 Laravel 模型?

Laravel上传文件无法写入目录

Homebrew PHP 似乎没有链接

Laravel Eloquent 多态一对一?

Laravel 隐藏属性.例如密码 - 安全

如何在 Laravel 中 Refresh刷新用户对象?

Laravel 单元测试依赖注入

有没有办法让表名自动添加到 Eloquent 查询方法中?