├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md ├── workflows │ └── main.yml ├── label-package.json └── stale.yml ├── .styleci.yml ├── UPGRADING.md ├── src ├── Facades │ └── BladeHelper.php ├── BladeHelperServiceProvider.php └── BladeHelper.php ├── .phpunit.result.cache ├── CHANGELOG.md ├── LICENSE.md ├── composer.json ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: imliam 2 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /UPGRADING.md: -------------------------------------------------------------------------------- 1 | # Upgrading 2 | 3 | This project follows [semantic versioning](https://semver.org/) so any breaking versions should be noted here. 4 | 5 | Please remember that it is not guaranteed that this file will always be up-to-date and it is recommended to lock the dependency to the minor version. 6 | 7 | ## 1.0.0 - 2018-11-29 8 | 9 | - Initial release 10 | -------------------------------------------------------------------------------- /src/Facades/BladeHelper.php: -------------------------------------------------------------------------------- 1 | app->singleton('blade.helper', function () { 15 | return new BladeHelper($this->app->make('blade.compiler')); 16 | }); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | {"version":1,"defects":[],"times":{"ImLiam\\BladeHelper\\Tests\\Unit\\BladeHelperTest::custom_named_helpers_compile_correctly":0.05,"ImLiam\\BladeHelper\\Tests\\Unit\\BladeHelperTest::custom_unnamed_helpers_compile_correctly":0,"ImLiam\\BladeHelper\\Tests\\Unit\\BladeHelperTest::custom_helpers_without_echo_compile_correctly":0.001,"ImLiam\\BladeHelper\\Tests\\Unit\\BladeHelperTest::custom_helper_callbacks_compile_correctly":0,"ImLiam\\BladeHelper\\Tests\\Unit\\BladeHelperTest::custom_if_helpers_can_be_registered":0.001}} -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable project changes will be documented in this file. 4 | 5 | The changelog format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | 9 | ... 10 | 11 | ## [1.2.0](https://github.com/imliam/laravel-blade-helper/releases/tag/v1.2.0) - 2019-09-10 12 | 13 | - Updated for Laravel 6 14 | 15 | ## [1.1.0](https://github.com/imliam/laravel-blade-helper/releases/tag/v1.1.0) - 2019-07-10 16 | 17 | ## Added 18 | 19 | - Added `BladeHelper::if` method 20 | 21 | ## [1.0.0](https://github.com/imliam/laravel-blade-helper/releases/tag/v1.0.0) - 2018-11-29 22 | 23 | ### Added 24 | 25 | - Initial release 26 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Description 2 | 3 | Make it clear if the issue is a **bug**, an **enhancement** or just a **question**. The easiest way to indicate this is to prefix the title, e.g. `[Question] I have a question`. 4 | 5 | Provide a detailed description of the change or addition you are proposing. Include some screenshots or code examples if possible. 6 | 7 | ### Your environment 8 | 9 | If you're reporting a bug or asking a specific question, include as many relevant details about your environment so we can reproduce it. The more, the better. 10 | 11 | - Package version or last commit 12 | - Operating system and version 13 | - PHP version 14 | - Related package versions 15 | - … 16 | 17 | ## Context 18 | 19 | Why is this change important to you? How would you use it? How can it benefit other users? 20 | 21 | ## Possible implementation 22 | 23 | Not obligatory, but suggest an idea for implementing addition or change. 24 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Liam Hammett 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Pull request type 2 | 3 | What kind of pull request is this? Put an `x` in all the boxes that apply: 4 | 5 | - [ ] Bug fix (non-breaking change which fixes an issue) 6 | - [ ] New feature (non-breaking change which adds functionality) 7 | - [ ] Extend feature (non-breaking change which extends existing functionality) 8 | - [ ] Change feature (non-breaking change which either changes or refactors existing functionality) 9 | - [ ] Breaking change (fix or feature that would cause existing functionality to change) 10 | 11 | ## What does it change? 12 | 13 | Describe your changes in detail. 14 | 15 | ## Why this PR? 16 | 17 | Why is this change required? What problem does it solve? 18 | 19 | ## How has this been tested? 20 | 21 | Please describe in detail how you tested your changes (or are planning on testing them). 22 | 23 | ## Checklist 24 | 25 | To facilitate merging your change and the approval of this PR, please make sure you've reviewed and applied the following: 26 | 27 | - This PR addresses exactly one issue 28 | - All changes were made in a fork of this project (preferably also in a separate branch) 29 | - It follows the code style of this project 30 | - Tests were added to cover the changes 31 | - All previously existing tests still pass 32 | - If the change to the code requires a change to the documentation, it has been updated accordingly 33 | - You have read the notes on contributing to the project and adhere to the rules laid out 34 | 35 | If you're unsure about any of these, don't hesitate to ask. We're here to help! 36 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | - push 5 | - pull_request 6 | 7 | jobs: 8 | test: 9 | runs-on: ${{ matrix.os }} 10 | 11 | strategy: 12 | fail-fast: false 13 | matrix: 14 | os: [ubuntu-latest] 15 | php: [8.4, 8.3, 8.2] 16 | laravel: [^12.0, ^11.0] 17 | dependency-version: [prefer-lowest, prefer-stable] 18 | include: 19 | - laravel: ^11.0 20 | testbench: ^9.0 21 | - laravel: ^12.0 22 | testbench: ^10.0 23 | 24 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} - ${{ matrix.os }} 25 | 26 | steps: 27 | - name: Checkout code 28 | uses: actions/checkout@v4 29 | 30 | - name: Setup PHP 31 | uses: shivammathur/setup-php@v2 32 | with: 33 | php-version: ${{ matrix.php }} 34 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 35 | coverage: none 36 | 37 | - name: Install dependencies 38 | run: | 39 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 40 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 41 | 42 | - name: Execute tests 43 | run: vendor/bin/phpunit 44 | -------------------------------------------------------------------------------- /.github/label-package.json: -------------------------------------------------------------------------------- 1 | [ 2 | { "color": "#009800", "name": "Priority: Low" }, 3 | { "color": "#fbca04", "name": "Priority: Medium" }, 4 | { "color": "#eb6420", "name": "Priority: High" }, 5 | { "color": "#e11d21", "name": "Priority: Critical" }, 6 | { "color": "#009800", "name": "CLA: Signed" }, 7 | { "color": "#e11d21", "name": "CLA: Unsigned" }, 8 | { "color": "#000000", "name": "Status: Abandoned" }, 9 | { "color": "#009800", "name": "Status: Accepted" }, 10 | { "color": "#bfe5bf", "name": "Status: Available" }, 11 | { "color": "#e11d21", "name": "Status: Blocked" }, 12 | { "color": "#006b75", "name": "Status: Completed" }, 13 | { "color": "#cccccc", "name": "Status: In Progress" }, 14 | { "color": "#e11d21", "name": "Status: On Hold" }, 15 | { "color": "#000000", "name": "Status: Won't Do" }, 16 | { "color": "#fef2c0", "name": "Status: Pending" }, 17 | { "color": "#fbca04", "name": "Status: Review Needed" }, 18 | { "color": "#e11d21", "name": "Status: Revision Needed" }, 19 | { "color": "#e11d21", "name": "Type: Bug" }, 20 | { "color": "#fbca04", "name": "Type: Maintenance" }, 21 | { "color": "#84b6eb", "name": "Type: Enhancement" }, 22 | { "color": "#84b6eb", "name": "Type: New Feature" }, 23 | { "color": "#cc317c", "name": "Type: Question" }, 24 | { "color": "#e11d21", "name": "Pinned" }, 25 | { "color": "#e11d21", "name": "Security" }, 26 | { "color": "#7057ff", "name": "Good First Issue" }, 27 | { "color": "#cfd3d7", "name": "Duplicate" }, 28 | { "color": "#e4e669", "name": "Invalid" }, 29 | { "color": "#008672", "name": "Help Wanted" }, 30 | { "color": "#008672", "name": "Help Wanted" }, 31 | 32 | ] 33 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "imliam/laravel-blade-helper", 3 | "description": "An easier way to define custom Blade directives.", 4 | "keywords": [ 5 | "imliam", 6 | "laravel", 7 | "blade", 8 | "laravel-blade-helper" 9 | ], 10 | "homepage": "https://github.com/imliam/laravel-blade-helper", 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "Liam Hammett", 15 | "email": "liam@liamhammett.com", 16 | "homepage": "https://liamhammett.com", 17 | "role": "Developer" 18 | } 19 | ], 20 | "require": { 21 | "php": "^8.0", 22 | "illuminate/support": "^11.0|^12.0" 23 | }, 24 | "require-dev": { 25 | "phpunit/phpunit": "^11.0", 26 | "larapack/dd": "^1.0", 27 | "orchestra/testbench": "^9.0|^10.0", 28 | "mockery/mockery": "^1.0" 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "ImLiam\\BladeHelper\\": "src" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "ImLiam\\BladeHelper\\Tests\\": "tests" 38 | } 39 | }, 40 | "scripts": { 41 | "test": "vendor/bin/phpunit", 42 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 43 | "test:windows": "vendor\\bin\\phpunit", 44 | "test-coverage:windows": "vendor\\bin\\phpunit --coverage-html coverage" 45 | }, 46 | "config": { 47 | "sort-packages": true 48 | }, 49 | "extra": { 50 | "laravel": { 51 | "providers": [ 52 | "ImLiam\\BladeHelper\\BladeHelperServiceProvider" 53 | ], 54 | "aliases": { 55 | "BladeHelper": "ImLiam\\BladeHelper\\BladeHelperFacade" 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Configuration for probot-stale - https://github.com/probot/stale 2 | 3 | # Number of days of inactivity before an Issue or Pull Request becomes stale 4 | daysUntilStale: 60 5 | 6 | # Number of days of inactivity before a stale Issue or Pull Request is closed. 7 | # Set to false to disable. If disabled, issues still need to be closed manually, but will remain marked as stale. 8 | daysUntilClose: 30 9 | 10 | # Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable 11 | exemptLabels: 12 | - Pinned 13 | - Security 14 | - "Priority: Critical" 15 | - "Status: Completed" 16 | - "Status: In Progress" 17 | 18 | # Set to true to ignore issues in a project (defaults to false) 19 | exemptProjects: false 20 | 21 | # Set to true to ignore issues in a milestone (defaults to false) 22 | exemptMilestones: false 23 | 24 | # Label to use when marking as stale 25 | staleLabel: wontfix 26 | 27 | # Comment to post when marking as stale. Set to `false` to disable 28 | markComment: > 29 | This issue has been automatically marked as stale because it has not had 30 | recent activity. It will be closed if no further activity occurs. Thank you 31 | for your contributions. 32 | 33 | # Comment to post when removing the stale label. 34 | # unmarkComment: > 35 | # Your comment here. 36 | 37 | # Comment to post when closing a stale Issue or Pull Request. 38 | # closeComment: > 39 | # Your comment here. 40 | 41 | # Limit the number of actions per hour, from 1-30. Default is 30 42 | limitPerRun: 30 43 | 44 | # Limit to only `issues` or `pulls` 45 | # only: issues 46 | 47 | # Optionally, specify configuration settings that are specific to just 'issues' or 'pulls': 48 | # pulls: 49 | # daysUntilStale: 30 50 | # markComment: > 51 | # This pull request has been automatically marked as stale because it has not had 52 | # recent activity. It will be closed if no further activity occurs. Thank you 53 | # for your contributions. 54 | 55 | # issues: 56 | # exemptLabels: 57 | # - confirmed 58 | -------------------------------------------------------------------------------- /src/BladeHelper.php: -------------------------------------------------------------------------------- 1 | compiler = $compiler; 21 | } 22 | 23 | /** 24 | * Create a helper directive for a regular function. 25 | * 26 | * @param string $directiveName 27 | * @param string|callable $function 28 | * @param bool $shouldEcho 29 | */ 30 | public function directive(string $directiveName, $function = null, bool $shouldEcho = true) 31 | { 32 | $echo = $shouldEcho ? 'echo ' : ''; 33 | 34 | if (! is_string($function) && is_callable($function)) { 35 | $this->customDirectives[$directiveName] = $function; 36 | 37 | $this->compiler->directive($directiveName, function ($expression) use ($directiveName, $echo) { 38 | return "getDirective('{$directiveName}', {$expression}); ?>"; 39 | }); 40 | 41 | return; 42 | } 43 | 44 | $functionName = $function ?? $directiveName; 45 | 46 | $this->compiler->directive($directiveName, function ($expression) use ($functionName, $echo) { 47 | return ""; 48 | }); 49 | } 50 | 51 | /** 52 | * Get and execute a callback helper directive. 53 | * 54 | * @param string $name 55 | * @param mixed ...$arguments 56 | * 57 | * @return mixed 58 | */ 59 | public function getDirective(string $name, ...$arguments) 60 | { 61 | return $this->customDirectives[$name](...$arguments); 62 | } 63 | 64 | /** 65 | * Register an "if" statement directive. 66 | * 67 | * @param string $directiveName 68 | * @param callable $function 69 | * 70 | * @return void 71 | */ 72 | public function if(string $directiveName, callable $function) 73 | { 74 | $this->customDirectives[$directiveName] = $function; 75 | 76 | $this->compiler->directive($directiveName, function ($expression) use ($directiveName) { 77 | return "getDirective('{$directiveName}', {$expression})): ?>"; 78 | }); 79 | 80 | $this->compiler->directive('else'.ucfirst($directiveName), function ($expression) use ($directiveName) { 81 | return "getDirective('{$directiveName}', {$expression})): ?>"; 82 | }); 83 | 84 | $this->compiler->directive('end'.ucfirst($directiveName), function () { 85 | return ''; 86 | }); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code held within. They make the code freely available in the hope that it will be of use to other developers. It would be extremely unfair for them to suffer abuse or anger for their hard work. 10 | 11 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the world that developers are civilized and selfless people. 12 | 13 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient quality to benefit the project. Many developers have different skill sets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 14 | 15 | ## Viability 16 | 17 | When requesting or submitting new features, first consider whether it might be useful to others. Open source projects are used by many developers, who may have entirely different needs to your own. Think about whether or not your feature is likely to be used by other users of the project. 18 | 19 | ## Procedure 20 | 21 | Before filing an issue: 22 | 23 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 24 | - Check to make sure your feature suggestion isn't already present within the project. 25 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 26 | - Check the pull requests tab to ensure that the feature isn't already in progress. 27 | 28 | Before submitting a pull request: 29 | 30 | - Check the codebase to ensure that your feature doesn't already exist. 31 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 32 | - Note anything relevant in the [changelog file](CHANGELOG.md). 33 | 34 | ## Requirements 35 | 36 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 37 | 38 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 39 | 40 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 41 | 42 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 43 | 44 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 45 | 46 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 47 | 48 | - **Include emoji in your commit message** - Using [Gitmoji](https://gitmoji.carloscuesta.me/) as a guide, try to include an emoji at the start of a commit message to make it easily identifiable. 49 | 50 | **Happy coding**! 51 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintainer. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 44 | available at [http://contributor-covenant.org/version/1/4][version] 45 | 46 | [homepage]: http://contributor-covenant.org 47 | [version]: http://contributor-covenant.org/version/1/4/ 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Blade Helper 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/imliam/laravel-blade-helper.svg)](https://packagist.org/packages/imliam/laravel-blade-helper) 4 | [![Total Downloads](https://img.shields.io/packagist/dt/imliam/laravel-blade-helper.svg)](https://packagist.org/packages/imliam/laravel-blade-helper) 5 | [![License](https://img.shields.io/github/license/imliam/laravel-blade-helper.svg)](LICENSE.md) 6 | 7 | An easier way to define custom Blade directives. 8 | 9 | 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: 10 | 11 | ```php 12 | Illuminate\Support\Facades\Blade::directive('uppercase', function($expression) { 13 | return ""; 14 | }); 15 | ``` 16 | 17 | 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. 18 | 19 | 20 | 21 | - [Laravel Blade Helper](#laravel-blade-helper) 22 | - [💾 Installation](#💾-installation) 23 | - [📝 Usage](#📝-usage) 24 | - [Example Helper Directive](#example-helper-directive) 25 | - [Custom "if" Directive](#custom-if-directive) 26 | - [✅ Testing](#✅-testing) 27 | - [🔖 Changelog](#🔖-changelog) 28 | - [⬆️ Upgrading](#⬆️-upgrading) 29 | - [🎉 Contributing](#🎉-contributing) 30 | - [🔒 Security](#🔒-security) 31 | - [👷 Credits](#👷-credits) 32 | - [♻️ License](#♻️-license) 33 | 34 | 35 | 36 | ## 💾 Installation 37 | 38 | You can install the package with [Composer](https://getcomposer.org/) using the following command: 39 | 40 | ```bash 41 | composer require imliam/laravel-blade-helper:^1.0 42 | ``` 43 | 44 | ## 📝 Usage 45 | 46 | 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: 47 | 48 | ```php 49 | app('blade.helper')->directive(…); 50 | 51 | \ImLiam\BladeHelper\Facades\BladeHelper::directive(…); 52 | ``` 53 | 54 | This method accepts two arguments; the first is the name of the directive, and the second is the function that the directive should call: 55 | 56 | ```php 57 | // Define the helper directive 58 | BladeHelper::directive('uppercase', 'strtoupper'); 59 | 60 | // Use it in a view 61 | @uppercase('Hello world.') 62 | 63 | // Get the compiled result 64 | 65 | 66 | // See what's echoed 67 | "HELLO WORLD." 68 | ``` 69 | 70 | If no second argument is supplied, the directive will attempt to call a function of the same name: 71 | 72 | ```php 73 | // Define the helper directive 74 | BladeHelper::directive('join'); 75 | 76 | // Use it in a view 77 | @join('|', ['Hello', 'world']) 78 | 79 | // Get the compiled result 80 | 81 | 82 | // See what's echoed 83 | "Hello|world" 84 | ``` 85 | 86 | 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: 87 | 88 | - Type hint the arguments for the callback 89 | - Manipulate and use the individual arguments when the directive is called, instead of the raw expression as a string 90 | - Define a directive without having to only use it as a proxy to a helper function or class in another part of the application 91 | 92 | ```php 93 | // Define the helper directive 94 | BladeHelper::directive('example', function($a, $b, $c = 'give', $d = 'you') { 95 | return "$a $b $c $d up"; 96 | }); 97 | 98 | // Use it in a view 99 | @example('Never', 'gonna') 100 | 101 | // Get the compiled result 102 | getDirective('example', 'Never', 'gonna'); ?> 103 | 104 | // See what's echoed 105 | "Never gonna give you up" 106 | ``` 107 | 108 | 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: 109 | 110 | ```php 111 | // Define the helper directive 112 | BladeHelper::directive('log', null, false); 113 | 114 | // Use it in a view 115 | @log('View loaded…') 116 | 117 | // Get the compiled result 118 | 119 | 120 | // Nothing is echoed 121 | ``` 122 | 123 | ### Example Helper Directive 124 | 125 | One example of a custom Blade helper is to wrap around [FontAwesome 4](https://fontawesome.com/v4.7.0/) icons to make it more convenient to add alternate text for the sake of accessibility: 126 | 127 | ```php 128 | // Define the helper directive 129 | BladeHelper::directive('fa', function(string $iconName, string $text = null, $classes = '') { 130 | if (is_array($classes)) { 131 | $classes = join(' ', $classes); 132 | } 133 | 134 | $text = $text ?? $iconName; 135 | 136 | return "{$text}"; 137 | }); 138 | 139 | // Use it in a view 140 | @fa('email', 'Envelope') 141 | ``` 142 | 143 | ### Custom "if" Directive 144 | 145 | Laravel Blade offers [a handy way](https://laravel.com/docs/5.8/blade#custom-if-statements) 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. 146 | 147 | An if statement can be defined in the same way as the directive method, but must be given a callable as its second argument: 148 | 149 | ```php 150 | BladeHelper::if('largestFirst', function(int $a, int $b): bool { 151 | return $a > $b; 152 | }); 153 | ``` 154 | 155 | Once defined, the helpers can be used directly in your Blade templates: 156 | 157 | ```html 158 | @largestFirst(1, 2) 159 | Lorem ipsum 160 | @elseLargestFirst(5, 3) 161 | dolor sit amet 162 | @else 163 | consectetur adipiscing elit 164 | @endLargestFirst 165 | ``` 166 | 167 | ## ✅ Testing 168 | 169 | ``` bash 170 | composer test 171 | ``` 172 | 173 | ## 🔖 Changelog 174 | 175 | Please see [the changelog file](CHANGELOG.md) for more information on what has changed recently. 176 | 177 | ## ⬆️ Upgrading 178 | 179 | Please see the [upgrading file](UPGRADING.md) for details on upgrading from previous versions. 180 | 181 | ## 🎉 Contributing 182 | 183 | Please see the [contributing file](CONTRIBUTING.md) and [code of conduct](CODE_OF_CONDUCT.md) for details on contributing to the project. 184 | 185 | ### 🔒 Security 186 | 187 | If you discover any security related issues, please email liam@liamhammett.com instead of using the issue tracker. 188 | 189 | ## 👷 Credits 190 | 191 | - [Liam Hammett](https://github.com/imliam) 192 | - [@bhuvidya](https://github.com/bhuvidya) for initially extracting the [original PR](https://github.com/laravel/framework/pull/24923) to [a package](https://github.com/bhuvidya/laravel-blade-helper) 193 | - [All Contributors](../../contributors) 194 | 195 | ## ♻️ License 196 | 197 | The MIT License (MIT). Please see the [license file](LICENSE.md) for more information. 198 | --------------------------------------------------------------------------------