Why is my library not attached when programmatically rendering a block? I have this block:

public function build() {
  $build = [
    '#attached' =&gt; [
      'library' =&gt; [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' =&gt; '&lt;!-- see template --&gt;',
  ];

  return $build;
}


Somewhere I am rendering this block via custom text filter:

{{ '[embed:block:mymodulemyblock]' | text_format }}


This is my text filter that replaces the "token" with the rendered block:

public function process($text, $langcode) {
  if (preg_match_all('/\[embed:.+\]/isU', $text, $matchCodes)) {
    foreach ($matchCodes[0] as $index =&gt; $token) {
      $parts = explode(':', $cleaned);
      array_splice($parts, 0, 1);

      $entityType = trim($parts[0]);
      $entityId = trim($parts[1]);
      $viewMode = isset($parts[2]) ? trim($parts[2]) : 'full';

      if ('block' == $entityType) {
        $rendered = '';

        if ($block = entity_load('block', $entityId)) {
          $replacement = entity_view($block, 'block');
          $rendered = drupal_render($replacement);
        }
      }
      $text = str_replace($token, $rendered, $text);

    }
  }
  return new FilterProcessResult($text);
}


It works fine, except the block's library isnt attached. Not even when I add this inside the block template:

{{ attach_library('mymodule/mylibrary') }}


When I place the block in the block layout it works fine.

Why isnt the library attached?



Edit

This is how I register the template for the block itself:

function mmodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodulemyblock' =&gt; array(
      'render element' =&gt; 'elements',
      'template' =&gt; 'block--foobar',
      'base hook' =&gt; 'block',
    ),
  );
}
I think it's because attached needs to be a separate element than your markup.

This is one render element for markup, with the attached attached to it:

$build = [
    '#attached' =&gt; [
      'library' =&gt; [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' =&gt; '&lt;!-- see template --&gt;',
  ];


The correct way to set up a build array is with the markup being a separate element:

$build = [];

$build['#markup'] = ['#markup' =&gt; '&lt;h1&gt;testing 123&lt;/h1'];

$build['#attached']['library'] = ['mymodule/mylibrary'];

return $build;