ContextualLinksPlaceholder.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Drupal\contextual\Element;
  3. use Drupal\Component\Utility\Crypt;
  4. use Drupal\Core\Site\Settings;
  5. use Drupal\Core\Template\Attribute;
  6. use Drupal\Core\Render\Element\RenderElement;
  7. use Drupal\Component\Render\FormattableMarkup;
  8. /**
  9. * Provides a contextual_links_placeholder element.
  10. *
  11. * @RenderElement("contextual_links_placeholder")
  12. */
  13. class ContextualLinksPlaceholder extends RenderElement {
  14. /**
  15. * {@inheritdoc}
  16. */
  17. public function getInfo() {
  18. $class = get_class($this);
  19. return [
  20. '#pre_render' => [
  21. [$class, 'preRenderPlaceholder'],
  22. ],
  23. '#id' => NULL,
  24. ];
  25. }
  26. /**
  27. * Pre-render callback: Renders a contextual links placeholder into #markup.
  28. *
  29. * Renders an empty (hence invisible) placeholder div with a data-attribute
  30. * that contains an identifier ("contextual id"), which allows the JavaScript
  31. * of the drupal.contextual-links library to dynamically render contextual
  32. * links.
  33. *
  34. * @param array $element
  35. * A structured array with #id containing a "contextual id".
  36. *
  37. * @return array
  38. * The passed-in element with a contextual link placeholder in '#markup'.
  39. *
  40. * @see _contextual_links_to_id()
  41. */
  42. public static function preRenderPlaceholder(array $element) {
  43. $token = Crypt::hmacBase64($element['#id'], Settings::getHashSalt() . \Drupal::service('private_key')->get());
  44. $attribute = new Attribute([
  45. 'data-contextual-id' => $element['#id'],
  46. 'data-contextual-token' => $token,
  47. ]);
  48. $element['#markup'] = new FormattableMarkup('<div@attributes></div>', ['@attributes' => $attribute]);
  49. return $element;
  50. }
  51. }