CommandWithAttachedAssetsTrait.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Drupal\Core\Ajax;
  3. use Drupal\Core\Asset\AttachedAssets;
  4. /**
  5. * Trait for Ajax commands that render content and attach assets.
  6. *
  7. * @ingroup ajax
  8. */
  9. trait CommandWithAttachedAssetsTrait {
  10. /**
  11. * The attached assets for this Ajax command.
  12. *
  13. * @var \Drupal\Core\Asset\AttachedAssets
  14. */
  15. protected $attachedAssets;
  16. /**
  17. * Processes the content for output.
  18. *
  19. * If content is a render array, it may contain attached assets to be
  20. * processed.
  21. *
  22. * @return string|\Drupal\Component\Render\MarkupInterface
  23. * HTML rendered content.
  24. */
  25. protected function getRenderedContent() {
  26. $this->attachedAssets = new AttachedAssets();
  27. if (is_array($this->content)) {
  28. if (!$this->content) {
  29. return '';
  30. }
  31. $html = \Drupal::service('renderer')->renderRoot($this->content);
  32. $this->attachedAssets = AttachedAssets::createFromRenderArray($this->content);
  33. return $html;
  34. }
  35. else {
  36. return $this->content;
  37. }
  38. }
  39. /**
  40. * Gets the attached assets.
  41. *
  42. * @return \Drupal\Core\Asset\AttachedAssets|null
  43. * The attached assets for this command.
  44. */
  45. public function getAttachedAssets() {
  46. return $this->attachedAssets;
  47. }
  48. }