Skip to content

Instantly share code, notes, and snippets.

@lcube45
Last active June 1, 2020 14:55
Show Gist options
  • Save lcube45/9679ff8fe8e08c07e2cdca3e85e9d16a to your computer and use it in GitHub Desktop.
Save lcube45/9679ff8fe8e08c07e2cdca3e85e9d16a to your computer and use it in GitHub Desktop.
Drupal 8 - créer un filtre de texte personnalisé
<?php
namespace Drupal\my_module\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* Makes the tables in the content show up using Bootstrap styling.
*
* @Filter(
* id = "table_style_filter",
* title = @Translation("Table styles"),
* description = @Translation("Adds the necessary markup to tables to render
* them via Bootstrap styling."),
* type = \Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
* )
*/
class TableStyleFilter 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'));
$bootstrap_classes = [
'table',
'table-sm',
'table-striped',
'table-hover'
];
foreach ($bootstrap_classes as $class) {
$classes[] = $class;
}
$new_element = clone $element;
$new_element->setAttribute('class', join(' ', array_unique($classes)));
$wrapper = $dom->createElement('div');
$wrapper->setAttribute('class', 'table-responsive');
$wrapper->appendChild($new_element);
$element->parentNode->replaceChild($wrapper, $element);
}
return new FilterProcessResult(Html::serialize($dom));
}
}
@lcube45
Copy link
Author

lcube45 commented Jun 1, 2020

Afin de formater les saisies de contenu dans un ckeditor, il est possible de créer des filtres de texte personnalisés à affecter au filtre de texte du ckeditor. Ici un exemple pour traiter les tableaux et les rendre "bootstrap" friendly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment