Join 25,000+ Laravel Developers and join the free Laravel Newsletter
Laravel Tag Helper
News / October 30, 2018

Laravel Tag Helper

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:

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

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

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

The output will look like you’d expect:

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

Another built-in helper is the link helper:

<a route="home">Home</a>
<a route="profile" :route-parameters="[$user->id()]">
  Home
</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:

<?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
    }
}

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:

<?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)
    {
        // Example
        // <my-custom-link></my-custom-link>
        $element->setTag('a');
        $element->setAttribute('href', 'https://laravel-news.com');
    }
}

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.

This appeared first on Laravel News
Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.