Search
Blade Parser

Blade Parser

Compiling Custom Components

The default behavior of the compiler is to treat all custom component tags as if they were "normal" Blade component tags. However, we can provide custom compilers for our specific component tag prefixes and return custom-compiled output.

We create custom component tag compilers by implementing the Stillat\BladeParser\Contracts\CustomComponentTagCompiler interface. Each custom compiler implementation must implement the following method:

1<?php
2 
3public function compile(ComponentNode $component): ?string;

This method's return type can be a string, which should contain the custom compiled output. If the method returns null, the default component tag compiler will be utilized. If you wish to return no output, return an empty string.

#Example

The following example implements a custom component tag compiler. In addition, it disables the compilation of core components:

1<?php
2 
3use Stillat\BladeParser\Contracts\CustomComponentTagCompiler;
4use Stillat\BladeParser\Document\Document;
5use Stillat\BladeParser\Document\DocumentCompilerOptions;
6use Stillat\BladeParser\Nodes\Components\ComponentNode;
7 
8 
9class CustomCompiler implements CustomComponentTagCompiler
10{
11 public function compile(ComponentNode $component): ?string
12 {
13 return 'My custom compilation result!';
14 }
15}
16 
17$template = <<<'BLADE'
18<a-custom />
19<x-profile />
20BLADE;
21 
22$doc = Document::fromText(
23 $template,
24 customComponentTags: ['a']
25);
26 
27$result = $doc->compile(new DocumentCompilerOptions(
28 customTagCompilers: ['a' => new CustomCompiler],
29 compileCoreComponentTags: false
30));

Custom Component Names

You may have noticed that we supplied our custom component prefix to both our call to Document::fromText, and have specified it again as part of our DocumentCompilerOptions. This is because parsing and compilation are two distinct steps, and compilation of a Document instance is always optional.

Our example would produce the following results:

1My custom compilation result!
2<x-profile />

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.