Search
Blade Parser

Blade Parser

HTML Fragments

The Blade Parser library supports the concept of "HTML fragments," or the parsing of invalid HTML documents. This feature exists to help provide additional context to the parsed Blade constructs, such as where they appear within a document.

The following example demonstrates how we can use the HTML fragments feature to retrieve nodes based on their surrounding context:

1<?php
2 
3use Stillat\BladeParser\Nodes\AbstractNode;
4use Stillat\BladeParser\Document\Document;
5 
6$template = <<<'BLADE'
7 <{{ $element }} class="{{ $classList }}" {{ $attributes }}>
8 {{ $text }}
9 </{{ $closeElement }}>
10BLADE;
11 
12$doc = Document::fromText($template)
13 ->resolveFragments();
14 
15// Returns " $element $closeElement "
16$doc->getNodes()->where(fn(AbstractNode $n) => $n->isInHtmlTagName())
17 ->map(fn($n) => $n->innerContent)->join('');
18 
19// Returns " $classList "
20$doc->getNodes()->where(fn(AbstractNode $n) => $n->isInHtmlParameter())
21 ->map(fn($n) => $n->innerContent)->join('');
22 
23// Returns " $text "
24$doc->getNodes()->where(fn(AbstractNode $n) => $n->isBetweenHtmlFragments())
25 ->map(fn($n) => $n->innerContent)->join('');
26 
27// Returns " $attributes "
28$doc->getNodes()->where(fn(AbstractNode $n) => $n->isInHtmlTagContent())
29 ->map(fn($n) => $n->innerContent)->join('');

The following method descriptions may be helpful when interacting with the HTML fragments feature:

  • inHtmlTagName: Tests if the node appears inside an HTML tag's name.

  • isInHtmlParameter: Tests if the node appears within an HTML tag parameter or attribute at any point.

  • isInHtmlTagContent: Tests if the node appears within the HTML tag's content (after the tag name but before the > or />) and if it is not part of an HTML parameter or attribute.

  • isBetweenHtmlFragments: Tests if the node appears as part of an HTML tag's content and can be used to test if all the previous tests return false.

Similar to Document Structures, generating HTML fragments is an optional step, and we must call the resolveFragments method for the HTML content of the document to be parsed and Blade positions analyzed.

#Changing HTML Fragment Properties

Unlike most node types, updating the properties of HTML fragment nodes is not supported at this time.

#Available Methods

#resolveFragments

Resolves the Document's HTML fragments.

1<?php
2 
3use Stillat\BladeParser\Document\Document;
4 
5public function resolveFragments(): Document;

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.