如何将自定义函数传递给 Laravel Blade 模板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32430255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:18:45  来源:igfitidea点击:

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

laravellaravel-blade

提问by wobsoriano

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.

是否可以将自定义函数传递给刀片模板?谢谢你。

回答by Joseph Silber

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

您不必任何东西传递给刀片。如果你定义了你的函数,你可以从blade中使用它。



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


Now just use the function directly in blade:

现在直接在blade中使用该函数:

{{ trim_characters($string) }}