Creating HTML Macros

Problem

You'd like to extend the HTML facade with additional functionality.

Solution

Use the HTML::macro() method.

HTML::macro() allows you to extend the HTML facade with your own methods.

First you register a macro, then later you can access the macro as you would any of the HTML methods.

Let's say you add the following code to your app/start/global.php file.

HTML::macro('sumthin', function()
{
    return '<sumthin>default</sumthin>';
});

Then later, in a Blade template, you can access it.

{{ HTML::sumthin() }}

This would output the following.

<sumthin>default</sumthin>

Add macros that take arguments

Let's update the sumthin macro to take three arguments. First the implementation.

HTML::macro('sumthin', function($value, $count = 10, $start = 1)
{
    $build = array();
    while ($count > 0)
    {
        $build[] = sprintf('<sumthin index="%s">%s</sumthin>',
          $start, $value);
        $start += 1;
        $count -= 1;
    }
    return join("\n", $build);
});

Now HTML::sumthin() has one required argument and two optional ones. If you don't pass the required argument, Laravel will generate an error.

Use it in a template.

{{ HTML::sumthin('test', 5) }}

The output would be.

<sumthin index="1">test</sumthin>
<sumthin index="2">test</sumthin>
<sumthin index="3">test</sumthin>
<sumthin index="4">test</sumthin>
<sumthin index="5">test</sumthin>

Discussion

Examine the source code.

If you look at HtmlBuilder.php in your vendor/laravel/src/Illuminate\Html directory you can see several undocumented public methods of the HTML facade that you can use in your macros.

Your macro code doesn't have access to $this, but you can call any of the following handy methods:

You even can call other macros from your macro.

comments powered by Disqus