如何将自定义函数传递给 Laravel Blade 模板?
How to pass a custom function to a Laravel Blade template?
我有一个自定义函数,我想在 blade 模板中传递它。这是函数:
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 );
是否可以将自定义函数传递给 blade 模板?谢谢。
您不必传递任何东西给blade。如果您定义了函数,则可以从 blade.
使用它
- 创建一个新的
app/helpers.php
文件。
- 将您的
trim_characters
函数添加到其中。
- Add that file to your
composer.json
file.
- 运行
composer dump-autoload
.
现在直接使用blade中的函数即可:
{{ trim_characters($string) }}
另一种方法是注入服务。请参阅 https://laravel.com/docs/6.x/blade#service-injection
中的文档
在 class 中定义你的函数然后将它注入你的 Blade
class Foo {
trim_characters($string) {....}
}
然后在您的 blade 文件中
@inject('foo', 'Foo')
<div>{{ $foo->trim_characters($string) }}</div>
我有一个自定义函数,我想在 blade 模板中传递它。这是函数:
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 );
是否可以将自定义函数传递给 blade 模板?谢谢。
您不必传递任何东西给blade。如果您定义了函数,则可以从 blade.
使用它- 创建一个新的
app/helpers.php
文件。 - 将您的
trim_characters
函数添加到其中。 - Add that file to your
composer.json
file. - 运行
composer dump-autoload
.
现在直接使用blade中的函数即可:
{{ trim_characters($string) }}
另一种方法是注入服务。请参阅 https://laravel.com/docs/6.x/blade#service-injection
中的文档在 class 中定义你的函数然后将它注入你的 Blade
class Foo {
trim_characters($string) {....}
}
然后在您的 blade 文件中
@inject('foo', 'Foo')
<div>{{ $foo->trim_characters($string) }}</div>