data-align attribute on <img>
tags to align images."),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
* )
*/
class FilterAlign extends FilterBase {
/**
* {@inheritdoc}
*/
public function process($text, $langcode) {
$result = new FilterProcessResult($text);
if (stristr($text, 'data-align') !== FALSE) {
$dom = Html::load($text);
$xpath = new \DOMXPath($dom);
foreach ($xpath->query('//*[@data-align]') as $node) {
// Read the data-align attribute's value, then delete it.
$align = $node->getAttribute('data-align');
$node->removeAttribute('data-align');
// If one of the allowed alignments, add the corresponding class.
if (in_array($align, ['left', 'center', 'right'])) {
$classes = $node->getAttribute('class');
$classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
$classes[] = 'align-' . $align;
$node->setAttribute('class', implode(' ', $classes));
}
}
$result->setProcessedText(Html::serialize($dom));
}
return $result;
}
/**
* {@inheritdoc}
*/
public function tips($long = FALSE) {
if ($long) {
return $this->t('
You can align images, videos, blockquotes and so on to the left, right or center. Examples:
<img src="" data-align="left" />
<img src="" data-align="center" />
<img src="" data-align="right" />
<video src="" data-align="center" />
data-align="center"
), but also videos, blockquotes, and so on.');
}
}
}