I\'m trying to create a blade directive to highlight some words that will return from my search query.
This is my blade directive:
class AppServiceProvid
The best way to accomplish this task is exactly as @Everrett suggested.
I checked through the blade code, and this is exactly how the laravel team has to do it as well.
If you look through vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/CompilesHelpers.php
, at the compileDd
function, you'll notice that they use $arguments
instead of $expression
like they do in all of the other compile functions found in vendor/laravel/framework/src/Illuminate/View/Compilers/Concerns/
// CompilesHelpers.php
protected function compileDd($arguments)
{
return "";
}
//CompilesConditionals.php
protected function compileIf($expression)
{
return "";
}
And if you look at vendor/symfony/var-dumper/Resources/functions/dump.php
you'll see that Laravel handles variable arguments with ...
splat notation in the dd
function.
if (!function_exists('dd')) {
function dd(...$vars)
{
}}
So you could do a directive like: (I put my custom function in app\helpers) If you do the same, you need to make sure to escape the backslashes.
Blade::directive('customFunc', function ($expression) {
return "";
});
and a custom function like:
/**
* Custom function to demonstrate usage
* @param mixed ...$args
* @return void
*/
function customFunc(...$args): void {
// Extract variables //
// Use pad to get expected args, and set unset to null //
list($arg1, $arg2, $arg3) = array_pad($args, 3, null);
// Echo out args //
echo "arg1: ${arg1} | arg2: ${arg2} | arg3: {$arg3}";
}
run php artisan view:clear
And then use the directive:
@customFunc('hello','wonderful', 'world')
// Returns:
arg1: hello | arg2: wonderful | arg3: world
// Using
@customFunc('hello', 'world')
// Returns:
arg1: hello | arg2: world | arg3:
The best reason to do it this way is so that if your function evolves or changes, you only need to modify the underlining function. You wont have to clear views every time you change the code.