Monday 6 August 2018
How to pass a custom function to a Laravel Blade template?
Answer
Answer
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.
Answer
You don't have to pass anything to blade. If you define your function, you can use it from 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
.
Now just use the function directly in blade:
{{ trim_characters($string) }}
Subscribe to:
Post Comments (Atom)
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
-
According to my understanding, and my calculator, cos(90 degrees) equals 0 . In my code, I have a funct...
No comments:
Post a Comment