• Stars
    star
    236
  • Rank 164,090 (Top 4 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 5 years ago
  • Updated 12 months ago

Reviews

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

Repository Details

Add powerful HTML tag helpers to your Laravel application

Laravel Tag Helpers

Latest Version on Packagist Build Status Quality Score Total Downloads

This package allows you to register custom "tag helpers" in your Laravel application. These helpers can modify the HTML code.

For example, instead of this:

<form method="post">
    <input type="hidden" name="_method" value="DELETE">
    <input type="hidden" name="_token" value="csrf-token">    
</form>

You can use custom tag helpers to turn this code into this:

<form csrf method="delete">

</form> 

Installation

You can install the package via composer:

composer require beyondcode/laravel-tag-helper

The package will automatically register itself.

Usage

You can create your own Tag Helper, by creating a new class and extend from the BeyondCode\TagHelper\Helper class. Within this class you can define on which HTML elements and attributes your helper should be triggered:

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomTagHelper extends Helper
{
    protected $targetAttribute = 'custom';

    protected $targetElement = 'div';

    public function process(HtmlElement $element)
    {
        // Manipulate the DOM element
    }
}

To use and apply this tag helper, you need to register it. Typically you would do this in the AppServiceProvider boot() method or a service provider of your own.

TagHelper::helper(CustomTagHelper::class);

Since you only register the class name of the custom tag helper, you can use dependency injection inside of your custom helper class.

Binding your helper to HTML elements and attributes

In your custom tag helper, you can use the $targetAttribute and $targetElement properties to specify which HTML element (div, form, a, etc.) and which attributes (<div custom="value />, <form method="post">, etc.) you want to bind this helper to.

If you do not provide a targetElement on your own, this package will use a * as a wildcard in order to target all elements with a specific attribute, like this:

class CustomTagHelper extends Helper
{
    protected $targetAttribute = 'my-attribute';
    
    // ...
    
}

This tag helper would be called for every HTML element that has a my-attribute attribute.

Manipulating DOM Elements

Once your tag helper successfully matches one or multiple HTML elements, the process method of your tag helper will be called.

Inside of this method, you can manipulate the HTML element.

Available features:

Changing the HTML element tag

In this example, we are binding our helper to HTML elements <my-custom-link href="/"></my-custom-link>. In the process method, we can then change the tag internally to a to render this as a link.

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomLink extends Helper
{
    protected $targetElement = 'my-custom-link';

    public function process(HtmlElement $element)
    {
        $element->setTag('a');
    }
}

Manipulating Attributes

You can also add, edit or delete HTML element attributes.

In this example, we are binding our helper to all link tags that have a custom route attribute. We then update the href attribute of our link, remove the route attribute and add a new title attribute.

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomLink extends Helper
{
    protected $targetAttribute = 'route';
    
    protected $targetElement = 'a';

    public function process(HtmlElement $element)
    {
        $element->setAttribute('href', route($element->getAttribute('route')));
        
        $element->removeAttribute('route');
        
        $element->setAttribute('title', 'This is a link.');
    }
}

Manipulating Outer / Inner Text

Your custom tag helpers can you manipulate the HTML that is inside or outside of the current element.

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomLink extends Helper
{
    protected $targetAttribute = 'add-hidden-field';
    
    protected $targetElement = 'form';

    public function process(HtmlElement $element)
    {
        $element->removeAttribute('add-hidden-field');
        
        $element->appendInnerText('<input type="hidden" name="hidden" />');
        
        // $element->prependInnerText('');
        // $element->setInnerText('');
    }
}

Passing variables to your tag helpers

You can pass attribute values to your tag helpers as you would usually pass attributes to HTML elements. Since the modifications of your tag helpers get cached, you should always return valid Blade template output in your modified attribute values.

You can not directly access the variable content inside of your tag helper, but only get the attribute string representation.

For example, to get the attribute value of the method attribute:

<form method="post"></form>

You can access this data, using the getAttribute method inside your helper:

<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomForm extends Helper
{
    protected $targetElement = 'form';

    public function process(HtmlElement $element)
    {
        $formMethod = $element->getAttribute('method');
    }
}

If you want to write Blade output, you sometimes need to know if the user passed a variable or function call, or a string value. To tell the difference, users can pass variable data by prefixing the attribute using a colon.

If you want to output this attribute into a blade template, you can then use the getAttributeForBlade method and it will either give you an escaped string representation of the attribute - or the unescaped representation, in case it got prefixed by a colon.

For example:

<a route="home">Home</a>
<?php

namespace BeyondCode\TagHelper\Helpers;

use BeyondCode\TagHelper\Helper;
use BeyondCode\TagHelper\Html\HtmlElement;

class CustomForm extends Helper
{
    protected $targetElement = 'a';

    protected $targetAttribute = 'route';

    public function process(HtmlElement $element)
    {
        $element->setAttribute('href', "{{ route(" . $element->getAttributeForBlade('route') . ") }}");
        
        $element->removeAttribute('route');
    }
}

This will output:

<a href="{{ route('home') }}">Home</a>

But if you pass a dynamic parameter like this:

<a :route="$routeVariable">Home</a>

This will output:

<a href="{{ route($routeVariable) }}">Home</a>

This way you do not need to manually care about escaping and detecting dynamic variables.

Built-In Helpers

This package ships with a couple useful tag helpers out of the box.

CSRF Helper

Just add a csrf attribute to any form element to automatically add the Laravel CSRF field to it.

<form csrf method="post">

</form>

Will become:

<form method="post">
    <input type="hidden" name="_token" value="csrf-token">    
</form>

Caveats

csrf needs to be in a line with another attribute.

// this works
<form
    csrf action="/posts"
    class="mt-8>
    
// this doesn't work
<form
    csrf
    action="/posts"
    class="mt-8>
    

Form Method Helper

When your form contains a method other then GET or POST, the helper will automatically add a _method hidden field with the correct value to your form.

<form method="delete">

</form>

Will become:

<form method="post">
    <input type="hidden" name="_method" value="DELETE">    
</form>

Link

When your a tags contains a route attribute, this helper will change the href to the appropriate route. You can also provide a route-parameters attribute, to pass additional parameters to the route generation.

Examples:

<a route="home">Home</a>

<a route="profile" :route-parameters="[$user->id()]">Home</a>

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

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 License File for more information.

More Repositories

1

laravel-websockets

Websockets for Laravel. Done right.
PHP
5,053
star
2

expose

A beautiful, fully open-source, tunneling service - written in pure PHP
PHP
4,147
star
3

laravel-er-diagram-generator

Generate entity relation diagrams from your Laravel model files.
PHP
1,858
star
4

laravel-query-detector

Laravel N+1 Query Detector
PHP
1,785
star
5

laravel-dump-server

Bring Symfony's Var-Dump Server to Laravel
PHP
1,477
star
6

laravel-self-diagnosis

Perform Self-Diagnosis Tests On Your Laravel Application
PHP
1,386
star
7

writeout.ai

Transcribe and translate your audio files - for free
PHP
1,287
star
8

laravel-mailbox

Catch incoming emails in your Laravel application
PHP
973
star
9

laravel-vouchers

Allow users to redeem vouchers that are bound to models.
PHP
601
star
10

laravel-credentials

Add encrypted credentials to your Laravel production environment.
PHP
572
star
11

laravel-view-xray

Take a look into your Laravel views
PHP
572
star
12

dusk-dashboard

A beautiful dashboard for your Laravel Dusk tests
PHP
559
star
13

laravel-confirm-email

Add email verification to your Laravel projects
PHP
532
star
14

laravel-server-timing

Add Server-Timing header information from within your Laravel apps.
PHP
528
star
15

laravel-comments

Add comments to your Laravel application
PHP
426
star
16

livewire-devtools

Chrome and Firefox DevTools extension for debugging Livewire applications
JavaScript
390
star
17

laravel-websockets-demo

Demo application to use with the Laravel WebSockets package.
PHP
382
star
18

laravel-favicon

Create dynamic favicons based on your environment settings.
PHP
343
star
19

laravel-debugbar-companion

The Laravel DebugBar companion app
Vue
292
star
20

tailwindcss-jit-cdn

Tailwind CSS JIT in your browser
JavaScript
229
star
21

laravel-ask-database

Query your database using natural language
PHP
218
star
22

laravel-tinker-server

Tinker with your variables while working on your Laravel application
PHP
207
star
23

banners

Create beautiful looking social images for your PHP packages
TypeScript
201
star
24

tailwind-jit-api

Use the full power of Tailwind CSS' new JIT compiler by including one script tag to your HTML.
JavaScript
166
star
25

laravel-visual-diff

Create visual diffs in your Laravel application tests.
PHP
161
star
26

github-now

Automatically generate your GitHub user profile page
PHP
140
star
27

nova-tinker-tool

Use the power of Tinker within your Nova application.
Vue
116
star
28

laravel-prose-linter

Syntax-aware proofreading for your Laravel application.
PHP
104
star
29

laravel-inline-translation

Add inline translation capabilities to your Laravel application.
PHP
104
star
30

httpdump

Easily inspect incoming HTTP Requests
PHP
104
star
31

forge-cli

An opinionated Laravel Forge CLI tool
PHP
100
star
32

laravel-masked-db-dump

Dump masked information from your database
PHP
96
star
33

nova-custom-dashboard-card

A Laravel Nova dashboard card that allows you to build custom dashboards.
Vue
86
star
34

slack-notification-channel

Laravel Slack notification channel with API token support instead of incoming webhooks.
PHP
85
star
35

helo-laravel

HELO Laravel helper package to add
PHP
84
star
36

chatgpt-clone

A ChatGPT clone using the new OpenAI chat completions API
PHP
81
star
37

laravel-scope-checks

Automatically convert your Eloquent scopes to boolean check methods.
PHP
78
star
38

laravel-package-tools

Use the make: commands that you know and love from Laravel - outside of Laravel.
PHP
71
star
39

laravel-fixed-window-limiter

PHP
69
star
40

invoker-community

63
star
41

tinkerwell-community

58
star
42

carbon-desktop-app

🎨 Create and share beautiful images of your source code - right from a native app.
JavaScript
57
star
43

nova-filterable-cards

Add custom filters to your Nova metric cards
Vue
56
star
44

tinkerwell-helper

Open Tinkerwell right from your Laravel apps.
PHP
55
star
45

laravel-sliding-window-limiter

Sliding Time Window Rate Limiter for Laravel
PHP
41
star
46

fathom-analytics-api

The unofficial Fathom Analytics API
PHP
39
star
47

laravelpackageboilerplate.com

PHP
36
star
48

skeleton-laravel

PHP
34
star
49

nova-laravel-update-card

Check if you're running the latest Laravel version right from your Nova dashboard.
PHP
34
star
50

windy-community

31
star
51

docs.beyondco.de

Documentation of the Beyond Code package.
HTML
22
star
52

nova-rss-card

Display custom RSS feeds on your Nova dashboard.
PHP
14
star
53

invoker-er-diagram-plugin

Generate ER Diagrams in Invoker
Vue
14
star
54

nova-installer

The Laravel Nova Package Installer
PHP
14
star
55

laravel-badges

Built live on stage at Laracon Australia 2019
PHP
13
star
56

helo-community

Repository to discuss technical HELO issues, feature requests and more
13
star
57

regexpress

12
star
58

invoker-test-toolkit

Detect, run and evaluate your applications PHPUnit tests in Invoker.
Vue
7
star
59

laragone

PHP
7
star
60

tinkerwell-web-docs

Tinkerwell Web documentation with inline code snippets
7
star
61

skeleton-php

PHP
7
star
62

forge-demo

PHP
6
star
63

devtoolsfortailwind-community

5
star
64

fathom-notifier

PHP
5
star
65

invoker-routes-plugin

A Invoker plugin that shows you a table for all of your registered Laravel routes
Vue
4
star
66

docs-example

Example repository to display the documentation structure
2
star
67

invoker-plugin-typings

1
star
68

github-notion-sync

Syncing issues of multiple repositories with a Notion database.
1
star