One of the analytics providers requires all the links to have a specific attribute sc:linkname
to track details. Drupal 8 filter works for linkname
but not with sc:
prefix. From https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 it looks like all attributes have default namespace (e.g. href => xlink:href
).
Add a comment
|
1 Answer
One way to solve this problem is to have a custom filter which processes the linkname
and convert to sc:linkname
.
<?php
namespace Drupal\my_module\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* Provides a filter to correct faulty and chopped off HTML.
*
* @Filter(
* id = "filter_html_attribute_namespace_fixer",
* title = @Translation("Add 'sc' namespace to HTML attribute 'linkname'"),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE,
* weight = 10
* )
*/
class FilterHtmlAttributeNamespaceCorrector extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode) {
return new FilterProcessResult($this->addNamespace($text));
}
protected function addNamespace($text, $namespace = 'sc') {
$html_dom = Html::load($text);
$xpath = new \DOMXPath($html_dom);
foreach ($xpath->query('//a[@*]') as $element) {
foreach ($element->attributes as $name => $attribute) {
if ($name == 'linkname') {
$element->setAttribute('sc:linkname', $attribute->value);
$element->removeAttribute($name);
}
}
}
$text = Html::serialize($html_dom);
return trim($text);
}
}