如何将自定义函数传递给Laravel Blade模板? [英] How to pass a custom function to a Laravel Blade template?
本文介绍了如何将自定义函数传递给Laravel Blade模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义功能,我想在刀片模板中传递它.功能如下:
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;
}
用法如下:
$string = "A VERY VERY LONG TEXT";
trim_characters( $string );
是否可以将自定义功能传递给刀片模板?谢谢.
Is it possible to pass a custom function to the blade template? Thank you.
推荐答案
您不必传递任何刀片.如果定义了功能,则可以从blade中使用它.
You don't have to pass anything to blade. If you define your function, you can use it from blade.
- 创建一个新的
app/helpers.php
文件. - 向其中添加
trim_characters
函数. - 将该文件添加到您的
composer.json
文件中. - 运行
composer dump-autoload
.
- Create a new
app/helpers.php
file. - Add your
trim_characters
function to it. - Add that file to your
composer.json
file. - Run
composer dump-autoload
.
现在只需在刀片中直接使用该功能即可
Now just use the function directly in blade:
{{ trim_characters($string) }}
这篇关于如何将自定义函数传递给Laravel Blade模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文