Laravel Tag Helper

Packages

October 30th, 2018

laravel-tag-helper.png

Laravel Tag Helper is a package by Marcel Pociot for adding powerful HTML tag helpers to your Laravel application. As a quick example of what this package can do, it ships with a few helpers out of the box.

You might have a typical form with a hidden CSRF input:

1<form method="post" action="/profile">
2 @method('PUT')
3 @csrf
4</form>

With the Laravel Tag Helper package you can write the same as follows:

1<form csrf method="put">
2 {{-- ... --}}
3</form>

The output will look like you’d expect:

1<form method="post">
2 <input type="hidden" name="_method" value="PUT">
3 <input type="hidden" name="_token" value="csrf-token">
4</form>

Another built-in helper is the link helper:

1<a route="home">Home</a>
2<a route="profile" :route-parameters="[$user->id()]">
3 Home
4</a>

Custom Tag Helpers

The package works by registering tag helpers in a service provider’s boot() method. You can target specific elements and attributes that will trigger a process() call on the helper class during rendering.

Here’s an example from the project’s readme:

1<?php
2
3namespace BeyondCode\TagHelper\Helpers;
4
5use BeyondCode\TagHelper\Helper;
6use BeyondCode\TagHelper\Html\HtmlElement;
7
8class CustomTagHelper extends Helper
9{
10 protected $targetAttribute = 'custom';
11
12 protected $targetElement = 'div';
13
14 public function process(HtmlElement $element)
15 {
16 // Manipulate the DOM element
17 }
18}

Within the process() method you can customize the HTML element tag. For example, if you had a custom element that you wanted to render as a link:

1<?php
2
3namespace BeyondCode\TagHelper\Helpers;
4
5use BeyondCode\TagHelper\Helper;
6use BeyondCode\TagHelper\Html\HtmlElement;
7
8class CustomLink extends Helper
9{
10 protected $targetElement = 'my-custom-link';
11
12 public function process(HtmlElement $element)
13 {
14 // Example
15 // <my-custom-link></my-custom-link>
16 $element->setTag('a');
17 $element->setAttribute('href', 'https://laravel-news.com');
18 }
19}

Learn More

You can learn more by checking out the official readme on GitHub or installing the composer package with composer require beyondcode/laravel-tag-helper.

Filed in:

Paul Redmond

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