Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a custom function to a Laravel Blade template?

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.

like image 268
wobsoriano Avatar asked Sep 07 '15 02:09

wobsoriano


People also ask

Can we write PHP code in blade template Laravel?

Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

What is the advantage of Laravel blade template?

The main advantage of using the blade template is that we can create the master template, which can be extended by other files.


2 Answers

You don't have to pass anything to blade. If you define your function, you can use it from blade.


  1. Create a new app/helpers.php file.
  2. Add your trim_characters function to it.
  3. Add that file to your composer.json file.
  4. Run composer dump-autoload.

Now just use the function directly in blade:

{{ trim_characters($string) }}
like image 126
Joseph Silber Avatar answered Oct 09 '22 05:10

Joseph Silber


Another approach is injecting service. See docs at https://laravel.com/docs/6.x/blade#service-injection

Define your function inside a class then inject it inside your Blade

class Foo {
    trim_characters($string) {....}
}

Then in your blade file

@inject('foo', 'Foo')

<div>{{ $foo->trim_characters($string) }}</div>
like image 23
GusDeCooL Avatar answered Oct 09 '22 05:10

GusDeCooL