How to get attachments out of a twig file 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' =&gt; 'pullquote',
      '#quote_text' =&gt; $quote_text,
      '#attribution_name' =&gt; $attribution_name,
      '#attribution_title' =&gt; $attribution_title,
      '#size' =&gt; $size,
    ];

    $response = new AjaxResponse();
    $response-&gt;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|\Drupal\Component\Render\MarkupInterface
   *   HTML rendered content.
   */
  protected function getRenderedContent() {
    $this-&gt;attachedAssets = new AttachedAssets();
    if (is_array($this-&gt;content)) {
      $html = \Drupal::service('renderer')-&gt;renderRoot($this-&gt;content);
      $this-&gt;attachedAssets = AttachedAssets::createFromRenderArray($this-&gt;content);
      return $html;
    }
    else {
      return $this-&gt;content;
    }
  }


Unfortunately, AttachedAssets::createFromRenderArray misses libraries added within twig.
Usually ajax commands which add html are able to catch attachments bubbling up when they render the content. Don't know EmbedInsertCommand(). The name clearly says it is an command inserting html, so it should be able to do it.

For commands not able to handle attachments you can render the content already in the controller and add the attachments to the response here:

  $response = new AjaxResponse();
  $html = \Drupal::service('renderer')-&gt;renderRoot($build);
  $response-&gt;addCommand(new EmbedInsertCommand($html));
  $response-&gt;setAttachments($build['#attached']);
  return $response;


This is only a workaround, not the recommend way, because Ajax does some more processing of the attachments before adding them to the response, but for a single command this should be OK.