Skip to content

Instantly share code, notes, and snippets.

@Mykola-Veryha
Created January 26, 2020 13:49
Show Gist options
  • Save Mykola-Veryha/996096abd4d700576d351b3a8a297af4 to your computer and use it in GitHub Desktop.
Save Mykola-Veryha/996096abd4d700576d351b3a8a297af4 to your computer and use it in GitHub Desktop.
Create own custom CKEditor filter
<?php
namespace Drupal\MODULE_NAME\Plugin\Filter;
use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;
/**
* Filter Link Title attribute.
*
* @Filter(
* id = "custom_link_title_html",
* title = @Translation("Link Title Filter"),
* description = @Translation("Add text (new window) to links in content."),
* type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE,
* )
*/
class LinkTitleFilter extends FilterBase {
/**
* Performs the filter processing.
*
* @param string $text
* The text string to be filtered.
* @param string $langcode
* The language code of the text to be filtered.
*
* @return \Drupal\filter\FilterProcessResult
* The filtered text, wrapped in a FilterProcessResult object, and possibly
* with associated assets, cacheability metadata and placeholders.
*
* @see \Drupal\filter\FilterProcessResult
*/
public function process($text, $langcode) {
$html = Html::load($text);
$links = $html->getElementsByTagName('a');
/** @var \DOMElement $link */
foreach ($links as $link) {
$target_attribute = $link->getAttribute('target');
$title_name = $link->nodeValue;
if ($target_attribute === '_blank') {
$link->setAttribute('title', $title_name . " " . $this->t("(new window)"));
}
}
$text = Html::serialize($html);
return new FilterProcessResult($text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment