Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass arguments in a custom blade directive?

In Laravel 5.1, I am trying to create a very basic blade directive:

Blade::directive('hello', function ($planet) {
    return 'Hello ' . $planet;
});

When I write:

@hello('world')

It returns:

Hello ('world')

I want:

Hello world

Yes I can remove these brackets manually but is it a bug in Laravel or what? How can I get world instead of (world) as the value of $planet.

like image 638
Homo Sapien Avatar asked Aug 22 '15 13:08

Homo Sapien


1 Answers

Try this :

Blade::directive('hello', function ($planet) {
    return "<?php echo 'Hello' . $planet ?>";
});

@hello('world'); // => Hello world

You can also pass an array instead of string, in that case you have to define how the array should be handled in the return value, here's an example:

Blade::directive('hello', function ($value) {
    if (is_array($value)) {
       return "<?php echo 'Hello' . $value[0] . ' and ' . $value[1] ?>";
    }

    if (is_string($planets)) {
       return "<?php echo 'Hello' . $value ?>";
    }

    // fallback when value is not recognised
    return "<?php echo 'Hello' ?>";
});

@hello('world'); // => Hello world
@hello(['world', 'mars']); // => Hello world mars
like image 161
zianwar Avatar answered Nov 08 '22 14:11

zianwar