如何将自定义函数传递给Laravel Blade模板? [英] How to pass a custom function to a Laravel Blade template?

查看:61
本文介绍了如何将自定义函数传递给Laravel Blade模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义功能,我想在刀片模板中传递它.功能如下:

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;
}

用法如下:

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

是否可以将自定义功能传递给刀片模板?谢谢.

Is it possible to pass a custom function to the blade template? Thank you.

推荐答案

您不必传递任何刀片.如果定义了功能,则可以从blade中使用它.

You don't have to pass anything to blade. If you define your function, you can use it from blade.

  1. 创建一个新的app/helpers.php文件.
  2. 向其中添加trim_characters函数.
  3. 将该文件添加到您的composer.json文件中.
  4. 运行composer dump-autoload.
  1. Create a new app/helpers.php file.
  2. Add your trim_characters function to it.
  3. Add that file to your composer.json file.
  4. Run composer dump-autoload.


现在只需在刀片中直接使用该功能即可


Now just use the function directly in blade:

{{ trim_characters($string) }}

这篇关于如何将自定义函数传递给Laravel Blade模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆