如何将自定义函数传递给 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
How to pass a custom function to a Laravel Blade template?
提问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中使用它。
- 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
.
- 创建一个新
app/helpers.php
文件。 - 将您的
trim_characters
功能添加到其中。 - 将该文件添加到您的
composer.json
文件中。 - 运行
composer dump-autoload
。
Now just use the function directly in blade:
现在直接在blade中使用该函数:
{{ trim_characters($string) }}