Examples

The AddAttributeValueToElements normalizer can be used to add a value to a list of space-separated values. For instance, it can add a link type to a link's rel, or a class name to an element's class.

In the following example, we target all a elements with the XPath query //a in order to add ugc to the list of link types stored in the element's rel attribute.

use s9e\TextFormatter\Configurator\TemplateNormalizations\AddAttributeValueToElements;

// Create a new configurator and enable the Autolink plugin
$configurator = new s9e\TextFormatter\Configurator;
$configurator->Autolink;

// Add our custom normalizer
$configurator->templateNormalizer->add(
    new AddAttributeValueToElements('//a', 'rel', 'ugc')
);

extract($configurator->finalize());

$text = 'https://example.org';
$xml  = $parser->parse($text);
$html = $renderer->render($xml);

echo $html;
<a href="https://example.org" rel="ugc">https://example.org</a>

Set loading="lazy" on images

In the following example, we use the SetAttributeOnElements normalizer to add a loading attribute to images that do not have one.

use s9e\TextFormatter\Configurator\TemplateNormalizations\SetAttributeOnElements;

// Create a new configurator and enable the Autoimage plugin
$configurator = new s9e\TextFormatter\Configurator;
$configurator->Autoimage;

// Add our custom normalizer
$configurator->templateNormalizer->add(
    new SetAttributeOnElements('//img[not(@loading)]', 'loading', 'lazy')
);

extract($configurator->finalize());

$text = 'https://example.org/img.png';
$xml  = $parser->parse($text);
$html = $renderer->render($xml);

echo $html;
<img src="https://example.org/img.png" loading="lazy">

Set nonce="{$NONCE}" on scripts

In the following example, we use the SetAttributeOnElements normalizer to add a nonce attribute to all script elements.

use s9e\TextFormatter\Configurator\TemplateNormalizations\SetAttributeOnElements;

// Create a new configurator
$configurator = new s9e\TextFormatter\Configurator;

// Add our custom normalizer before plugins are configured and templates are set
$configurator->templateNormalizer->add(
    new SetAttributeOnElements('//script', 'nonce', '{$NONCE}')
);

// Add a BBCode that creates a script element
$configurator->BBCodes->addCustom('[x]', '<script>alert(1)</script>');

extract($configurator->finalize());

$text = '[x]';
$xml  = $parser->parse($text);

// Set the value for $NONCE before rendering
$renderer->setParameter('NONCE', 'xxxx');
$html = $renderer->render($xml);

echo $html;
<script nonce="xxxx">alert(1)</script>