Laravel Blade Helper


June 21st, 2019


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:

1BladeHelper::directive('uppercase', function($expression) {
2 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:

1// Define the helper directive
2BladeHelper::directive('uppercase', 'strtoupper');
4// Use it in a view
5@uppercase('Hello world.')
7// Get the compiled result
8<?php echo strtoupper('Hello world.'); ?>
10// See what's echoed

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

1// Define the helper directive
2BladeHelper::directive('example', function($a, $b, $c = 'give', $d = 'you') {
3 return "$a $b $c $d up";
6// Use it in a view
7@example('Never', 'gonna')
9// Get the compiled result
10<?php echo app('blade.helper')->getDirective('example', 'Never', 'gonna'); ?>
12// See what's echoed
13"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:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners