Laravel Blade Helper

Laravel Blade Helper

Laravel Blade Helper is a package by Liam Hammett and provides an easier way to define custom blade directives:

When creating new custom Blade directives using theBlade::directive(…)method, the only parameter made available to manipulate is the expression passed through from the .blade.php file as a raw string. It seems to be rare that developers actually parse the contents of the expression itself within the directive, opting instead to pass the entire expression as arguments to a helper function or a method on another class.

For example:

BladeHelper::directive('uppercase', function($expression) {
    return "<?php echo strtoupper($expression); ?>";
});

As this seems to be the most common use case, this package attempts to help make these helper functions that little bit easier to define without the boilerplate of returning the string or having to consider what an expression may be when creating a directive.

The readme has plenty of useful examples, such as defining the directive and the function it calls. In this example, the directive is calling the underlying strtoupper built-in function:

// Define the helper directive
BladeHelper::directive('uppercase', 'strtoupper');

// Use it in a view
@uppercase('Hello world.')

// Get the compiled result
<?php echo strtoupper('Hello world.'); ?>

// See what's echoed
"HELLO WORLD."

The defined function can also be a closure and accepts multiple arguments making it easier to handle individual arguments in the function:

// Define the helper directive
BladeHelper::directive('example', function($a, $b, $c = 'give', $d = 'you') {
    return "$a $b $c $d up";
});

// Use it in a view
@example('Never', 'gonna')

// Get the compiled result
<?php echo app('blade.helper')->getDirective('example', 'Never', 'gonna'); ?>

// See what's echoed
"Never gonna give you up"

You can learn more about this package, get full installation instructions, and view the source code on GitHub at imliam/laravel-blade-helper.


Filed in: News


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Full Stack Software Engineer
Atlanta, GA or Remote
Voxie
Laravel/PHP Developer
Chicago, IL
Neon One
Software Engineer, Web Applications
Vaughan, ON, Canada
Blast Motion
Contract Services Software Engineer (Laravel | Vue | Tailwind)
Remote
Riverbed Technology
Senior Laravel Developer
Wilmington, NC
GE Software Inc.
Senior Full Stack Developer (PHP | Vue | DDD)
Charleston, SC
MassageBook