ev3rlost's avatar

Custom blade directive name for a component

After Caleb announced Flux .... I was wondering:

How can you get a custom blade name like in Laravel?

I tried many different aproaches but none of them work.

I want to build my own component library and I want to use it like <lm:alert /> ... not x-lm:alert.

Can someone enlighten me? Thanks!

0 likes
1 reply
LaryAI's avatar
Level 58

To create a custom Blade directive that allows you to use a custom tag like <lm:alert /> in Laravel, you can follow these steps:

  1. Create a Custom Blade Compiler: Extend the Blade compiler to recognize your custom tags.

  2. Register the Custom Blade Compiler: Register your custom compiler in a service provider.

  3. Define the Custom Component: Create the component class and view.

Here’s a step-by-step guide:

Step 1: Create a Custom Blade Compiler

Create a new class that extends the default Blade compiler. This class will handle the parsing of your custom tags.

Step 2: Register the Custom Blade Compiler

In your AppServiceProvider or a custom service provider, register the custom compiler.

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\View\Compilers\CustomBladeCompiler;
use Illuminate\View\Engines\CompilerEngine;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('blade.compiler', function ($app) {
            $cachePath = $app['config']['view.compiled'];
            return new CustomBladeCompiler($app['files'], $cachePath);
        });

        $this->app->extend('view.engine.resolver', function ($resolver, $app) {
            $resolver->register('blade', function () use ($app) {
                return new CompilerEngine($app['blade.compiler']);
            });

            return $resolver;
        });
    }

    public function boot()
    {
        //
    }
}

Step 3: Define the Custom Component

Create a Blade component and its corresponding view. For example, create a component named Alert.

  1. Component Class: Create a new component class in app/View/Components/Alert.php.
namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    public $type;

    public function __construct($type = 'info')
    {
        $this->type = $type;
    }

    public function render()
    {
        return view('components.alert');
    }
}
  1. Component View: Create the view file in resources/views/components/alert.blade.php.
<div class="alert alert-{{ $type }}">
    {{ $slot }}
</div>

Usage

Now you can use your custom component in your Blade views like this:

<lm:alert type="success">
    This is a success alert!
</lm:alert>

This setup allows you to use custom tags like <lm:alert /> in your Blade templates, making your component library more intuitive and easier to use.

Please or to participate in this conversation.