我有一个自定义函数,我想在刀片模板中传递它。下面是函数:
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 );是否可以将自定义函数传递给刀片模板?谢谢。
发布于 2015-09-07 10:14:41
您不必将任何内容传递给blade。如果你定义了你的函数,你可以在刀片中使用它。
app/helpers.php文件。composer.json file.composer dump-autoload.中添加您的函数
现在只需在刀片中直接使用该函数:
{{ trim_characters($string) }}发布于 2021-12-27 02:58:00
另一种方法是注入服务。请参阅https://laravel.com/docs/6.x/blade#service-injection上的文档
在类中定义函数,然后将其注入到Blade中
class Foo {
trim_characters($string) {....}
}然后在您的刀片文件中
@inject('foo', 'Foo')
<div>{{ $foo->trim_characters($string) }}</div>https://stackoverflow.com/questions/32430255
复制相似问题