1

I have this block:

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

  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 => $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' => array(
      'render element' => 'elements',
      'template' => 'block--foobar',
      'base hook' => 'block',
    ),
  );
}
  • 1
    Btw. You should use \Drupal::service('renderer')->renderRoot() instead of drupal_render(). – kenorb Aug 4 '17 at 21:28
0

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' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

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

$build = [];

$build['#markup'] = ['#markup' => '<h1>testing 123</h1'];

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

return $build;
0

If you haven't figured this out yet, I'm pretty sure that you have to output {{ content }} in your twig template for the block. You can exclude other variables by doing {{ content|without('var1', 'var2') }}. That will ensure the attached library is actually attached.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.