Created
January 14, 2019 17:18
-
-
Save ahebrank/616efd8b446a40ccf3af47c4163421dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| diff --git a/src/Plugin/Field/FieldFormatter/EmbederatorFormatter.php b/src/Plugin/Field/FieldFormatter/EmbederatorFormatter.php | |
| index 305e71b..1bebf84 100644 | |
| --- a/src/Plugin/Field/FieldFormatter/EmbederatorFormatter.php | |
| +++ b/src/Plugin/Field/FieldFormatter/EmbederatorFormatter.php | |
| @@ -5,6 +5,7 @@ namespace Drupal\embederator\Plugin\Field\FieldFormatter; | |
| use Drupal\Core\Field\FormatterBase; | |
| use Drupal\Core\Field\FieldItemListInterface; | |
| use Drupal\Core\Field\FieldDefinitionInterface; | |
| +use Drupal\Compnonent\Utility\Html; | |
| /** | |
| * Plugin implementation of the default embederator (token replacing) formatter. | |
| @@ -41,6 +42,7 @@ class EmbederatorFormatter extends FormatterBase { | |
| try { | |
| $response = $client->request('GET', $url); | |
| $markup = (string) $response->getBody(); | |
| + $markup = $this->uniquify($markup); | |
| } | |
| catch (Exception $e) { | |
| $markup = '<p>Unable to load ' . $url . '</p>'; | |
| @@ -58,6 +60,7 @@ class EmbederatorFormatter extends FormatterBase { | |
| $elements = []; | |
| foreach ($items as $delta => $item) { | |
| $markup = $token->replace($embed_pattern_field['value'], ['embederator' => $entity]); | |
| + $markup = $this->uniquify($markup); | |
| $elements[$delta] = [ | |
| '#type' => 'processed_text', | |
| '#text' => $markup, | |
| @@ -80,4 +83,23 @@ class EmbederatorFormatter extends FormatterBase { | |
| && ($field_definition->getName() == 'embed_id')); | |
| } | |
| + /** | |
| + * Add a random suffix to ID attributes in DOM markup. | |
| + * | |
| + * See e.g., https://api.drupal.org/api/drupal/core%21modules%21filter%21src%21Plugin%21Filter%21FilterHtml.php/function/FilterHtml%3A%3AfilterAttributes/8.2.x. | |
| + */ | |
| + protected function uniquify($html) { | |
| + $suffix = uniqid(); | |
| + $html_dom = Html::load($html); | |
| + $xpath = new \DOMXPath($html_dom); | |
| + foreach ($xpath | |
| + ->query('//[id]') as $element) { | |
| + $id = $element->getAttribute('id'); | |
| + $id .= "-" . $suffix; | |
| + $element->setAttribute('id', $id); | |
| + } | |
| + $html = Html::serialize($html_dom); | |
| + return trim($html); | |
| + } | |
| + | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment