3 namespace Drupal\filter\Plugin\Filter;
5 use Drupal\Component\Utility\Html;
6 use Drupal\filter\FilterProcessResult;
7 use Drupal\filter\Plugin\FilterBase;
10 * Provides a filter to align elements.
13 * id = "filter_align",
14 * title = @Translation("Align images"),
15 * description = @Translation("Uses a <code>data-align</code> attribute on <code><img></code> tags to align images."),
16 * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE
19 class FilterAlign extends FilterBase {
24 public function process($text, $langcode) {
25 $result = new FilterProcessResult($text);
27 if (stristr($text, 'data-align') !== FALSE) {
28 $dom = Html::load($text);
29 $xpath = new \DOMXPath($dom);
30 foreach ($xpath->query('//*[@data-align]') as $node) {
31 // Read the data-align attribute's value, then delete it.
32 $align = $node->getAttribute('data-align');
33 $node->removeAttribute('data-align');
35 // If one of the allowed alignments, add the corresponding class.
36 if (in_array($align, ['left', 'center', 'right'])) {
37 $classes = $node->getAttribute('class');
38 $classes = (strlen($classes) > 0) ? explode(' ', $classes) : [];
39 $classes[] = 'align-' . $align;
40 $node->setAttribute('class', implode(' ', $classes));
43 $result->setProcessedText(Html::serialize($dom));
52 public function tips($long = FALSE) {
55 <p>You can align images, videos, blockquotes and so on to the left, right or center. Examples:</p>
57 <li>Align an image to the left: <code><img src="" data-align="left" /></code></li>
58 <li>Align an image to the center: <code><img src="" data-align="center" /></code></li>
59 <li>Align an image to the right: <code><img src="" data-align="right" /></code></li>
60 <li>… and you can apply this to other elements as well: <code><video src="" data-align="center" /></code></li>
64 return $this->t('You can align images (<code>data-align="center"</code>), but also videos, blockquotes, and so on.');