How do I get the attachments out a twig file and add them to a build array?
If there is a twig file with
{{ attach_library('mytheme/pullquote') }}
And because it’s in an ajax response, I need to get the attachments out without rendering the page, how do I get a new build array with that library attached?
In my controller:
$build['pullquote'] = [ '#theme' => 'pullquote', '#quote_text' => $quote_text, '#attribution_name' => $attribution_name, '#attribution_title' => $attribution_title, '#size' => $size, ]; $response = new AjaxResponse(); $response->addCommand(new EmbedInsertCommand($build)); return $response;
Because the library is added in twig and not in the build array, it’s not coming through in the response.
The EmbedInsertCommand is from the embed module, which entity_embed inherits from, at embed/src/Ajax/EmbedInsertCommand.php
which uses the CommandWithAttachedAssetsTrait, with this function:
/** * Processes the content for output. * * If content is a render array, it may contain attached assets to be * processed. * * @return string|DrupalComponentRenderMarkupInterface * HTML rendered content. */ protected function getRenderedContent() { $this->attachedAssets = new AttachedAssets(); if (is_array($this->content)) { $html = Drupal::service('renderer')->renderRoot($this->content); $this->attachedAssets = AttachedAssets::createFromRenderArray($this->content); return $html; } else { return $this->content; } }
Unfortunately, AttachedAssets::createFromRenderArray misses libraries added within twig.