• Stars
    star
    178
  • Rank 214,989 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 6 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An easier way to define custom Blade directives.

Laravel Blade Helper

Latest Version on Packagist Build Status CI Status Total Downloads License

An easier way to define custom Blade directives.

When creating new custom Blade directives using the Blade::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:

Illuminate\Support\Facades\Blade::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.

πŸ’Ύ Installation

You can install the package with Composer using the following command:

composer require imliam/laravel-blade-helper:^1.0

πŸ“ Usage

The BladeHelper object is bound to Laravel's service container with the name blade.helper and can be used by resolving that. A Facade is also made available for convenience. To define a helper, the directive(…) method is used:

app('blade.helper')->directive(…);

\ImLiam\BladeHelper\Facades\BladeHelper::directive(…);

This method accepts two arguments; the first is the name of the directive, and the second is the function that the directive should call:

// 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."

If no second argument is supplied, the directive will attempt to call a function of the same name:

// Define the helper directive
BladeHelper::directive('join');

// Use it in a view
@join('|', ['Hello', 'world'])

// Get the compiled result
<?php echo join('|', ['Hello', 'world']); ?>

// See what's echoed
"Hello|world"

The second argument can also take a callback. The advantage of a callback here over the typical Blade::directive(…) method Laravel offers is that the callback given can have specific parameters defined instead of just getting raw expression as a string. This brings several advantages to the process of creating a Blade helper directive:

  • Type hint the arguments for the callback
  • Manipulate and use the individual arguments when the directive is called, instead of the raw expression as a string
  • Define a directive without having to only use it as a proxy to a helper function or class in another part of the application
// 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"

By default, all of the helper directives will echo out their contents to the view when used. This can be disabled by passing false as the third argument:

// Define the helper directive
BladeHelper::directive('log', null, false);

// Use it in a view
@log('View loaded…')

// Get the compiled result
<?php log('View loaded…'); ?>

// Nothing is echoed

Example Helper Directive

One example of a custom Blade helper is to wrap around FontAwesome 4 icons to make it more convenient to add alternate text for the sake of accessibility:

// Define the helper directive
BladeHelper::directive('fa', function(string $iconName, string $text = null, $classes = '') {
    if (is_array($classes)) {
        $classes = join(' ', $classes);
    }

    $text = $text ?? $iconName;

    return "<i class='fa fa-{$iconName} {$classes}' aria-hidden='true' title='{$text}'></i><span class='sr-only'>{$text}</span>";
});

// Use it in a view
@fa('email', 'Envelope')

Custom "if" Directive

Laravel Blade offers a handy way to define custom "if" statement directives. The Blade Helper package offers an additional method to generate these directives, with if, elseif and endif variants all automatically generated.

An if statement can be defined in the same way as the directive method, but must be given a callable as its second argument:

BladeHelper::if('largestFirst', function(int $a, int $b): bool {
    return $a > $b;
});

Once defined, the helpers can be used directly in your Blade templates:

@largestFirst(1, 2)
    Lorem ipsum
@elseLargestFirst(5, 3)
    dolor sit amet
@else
    consectetur adipiscing elit
@endLargestFirst

βœ… Testing

composer test

πŸ”– Changelog

Please see the changelog file for more information on what has changed recently.

⬆️ Upgrading

Please see the upgrading file for details on upgrading from previous versions.

πŸŽ‰ Contributing

Please see the contributing file and code of conduct for details on contributing to the project.

πŸ”’ Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

πŸ‘· Credits

♻️ License

The MIT License (MIT). Please see the license file for more information.

More Repositories

1

awesome-livewire

πŸš€ A curated list of awesome resources related to Livewire. https://github.com/livewire/livewire
647
star
2

vscode-inline-parameters

An extension for Visual Studio Code that adds inline parameter annotations when calling a function.
TypeScript
197
star
3

laravel-env-set-command

Set a .env file variable from the command line.
PHP
110
star
4

php-unique-gmail-address

A package to ensure that a Gmail address is unique
PHP
68
star
5

Lua-Collections

A robust Lua collection class based on Laravel collections.
Lua
50
star
6

laravel-throttle-simultaneous-requests

Throttle the current user's requests based on how many requests are currently being executed.
PHP
46
star
7

tweet-markdown

Effortlessly turn a Tweet into beautiful markdown
PHP
10
star
8

shareable-link

Conveniently generate shareable URLs for various social media websites.
PHP
9
star
9

liamhammett.com-2017

PHP
6
star
10

php-name-of-person

Present names for English-language applications.
PHP
6
star
11

Transformice-Utility

The source code for the Transformice module #utility
Lua
5
star
12

tailwindcss-open-variant

Open variant for Tailwind CSS
JavaScript
5
star
13

php-catch-exit

Gracefully handle an unwanted exit statement.
PHP
4
star
14

laravel-macros

A collection of miscellaneous methods to extend some of Laravel's core classes through the use of macros and mixins
PHP
3
star
15

autoexec.cfg

My personal settings and configuration for playing CS:GO
AutoHotkey
2
star
16

php-indefinite-article

Determine the indefinite article of an English term
PHP
2
star
17

oauth2-transferwise

TransferWise OAuth 2.0 Client Provider for The PHP League OAuth2-Client
PHP
2
star
18

sass-utility-classes

CSS utility classes.
CSS
1
star
19

php-nhs-number

Utility class to validate, format and generate NHS numbers.
PHP
1
star
20

tfm.pics

PHP
1
star
21

php-modifiers

Adds the ability to apply a range of optional modifiers `! @ ~ + -` when calling your class methods to augment them with a unique syntax.
PHP
1
star
22

transformice-records

#records module for the game Transformice
Lua
1
star