How to add container around CKEditor table

This filter plugin example will wrap the table element inside the div and adds two bootstrap classes around it.

Add this plugin to your module and enable it on your text format.

File: my_module / src / Plugin / Filter / TableWrapperFilter.php
<?php namespace Drupal\my_module\Plugin\Filter; use Drupal\Component\Utility\Html; use Drupal\Core\Annotation\Translation; use Drupal\filter\Annotation\Filter; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; /** * Adds wrapper round the table. * * @Filter( * id = "table_wrapper_filter", * title = @Translation("Table wrapper"), * description = @Translation("Adds wrapper around the table"), * type = \Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE, * ) */ class TableWrapperFilter extends FilterBase { /** * {@inheritdoc} */ public function process($text, $langcode) { $dom = Html::load($text); $elements = $dom->getElementsByTagName('table'); if ($elements->length === 0) { return new FilterProcessResult(Html::serialize($dom)); } /** @var \DOMElement $element */ foreach ($elements as $element) { $classes = explode(' ', $element->getAttribute('class')); $wrapper = $dom->createElement('div'); $wrapper->setAttribute('class', 'w-100 table-responsive'); $wrapper->appendChild($new_element); $element->parentNode->replaceChild($wrapper, $element); } return new FilterProcessResult(Html::serialize($dom)); } }
Buy Me a Coffee at ko-fi.com

Add new comment