How to pass a custom function to a Laravel Blade template?

假装没事ソ 提交于 2019-12-18 11:21:44

问题


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

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


回答1:


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


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


来源:https://stackoverflow.com/questions/32430255/how-to-pass-a-custom-function-to-a-laravel-blade-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!