27

我有一个自定义函数,我想在刀片模板中传递它。这是功能:

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

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

4

2 回答 2

51

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


  1. 创建一个新app/helpers.php文件。
  2. 将您的trim_characters功能添加到其中。
  3. 将该文件添加到您的composer.json文件中。
  4. 运行composer dump-autoload

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

{{ trim_characters($string) }}
于 2015-09-07T02:14:41.037 回答
1

另一种方法是注入服务。请参阅https://laravel.com/docs/6.x/blade#service-injection上的文档

在一个类中定义你的函数,然后将它注入你的 Blade

class Foo {
    trim_characters($string) {....}
}

然后在你的刀片文件中

@inject('foo', 'Foo')

<div>{{ $foo->trim_characters($string) }}</div>
于 2021-12-27T02:57:59.567 回答