2

I created a custom module with a page controller that returns a Symfony response (Symfony\Component\HttpFoundation\Response). The thing is I don't want to render my custom theme in this controller, just the theme_base template in this module.

$build = array(
  'page' => array(
    '#theme' => 'theme_base',
    '#content' => $content,
    '#owner' => $owner,
    '#cache' => [
      'max-age' => 0,
    ],
    '#attached' => array(
      'library' => array(
        'my_module/library_name',
      ),
    ),
  ),
);

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new Response();
$response->setContent($html);

return $response;

I tried attaching the module library to $build, or including it directly in Twig template but this doesn't seem to work.

Any ideas why this is not working? Or is there maybe another way I could do this?

Thanks!

  • If you are displaying it in a page in drupal site itself then you don't need to use renderRoot(). The libraries will be attached since drupal renders the renderable array $build that you return. – Razeem Ahmad Apr 29 '18 at 14:09
  • I don't want to display it in a page. I would like to have it completely separate, only with whatever I put in my #theme_base template. – ptinca Apr 29 '18 at 14:16
2

After rendering of $build the attachments have bubbled up to $build['#attached'] and you can add them to a response, which implements AttachmentsInterface, for example an HtmlResponse:

$html = \Drupal::service('renderer')->renderRoot($build);
$response = new HtmlResponse();
$response->setContent($html);
$response->setAttachments($build['#attached']);
return $response;

To place the libraries on the page you have to enclose the page in an html render element

$build = [
  '#type' => 'html',
  'page' => [
     // content with attached libraries  
  ],
];

or implement the placeholders where the attachment will end up in a custom template, see template_preprocess_html().

  • I tried this, but now I get an error and still no attachments: "The website encountered an unexpected error. Please try again later. AssertionError: assert(is_string($chunk) || $chunk instanceof HtmlResponse) in assert() (line 259 of core/modules/big_pipe/src/Render/BigPipe.php). assert(, 'assert(is_string($chunk) || $chunk instanceof HtmlResponse)') (Line: 259)" – ptinca Apr 29 '18 at 14:45
  • The error was my mistake, sorry. Disregard the above comment. But I'm still not getting attachments. – ptinca Apr 29 '18 at 14:49
  • I think you need to enclose the page in an html render element to attach libraries: $build = ['#type' => 'html', 'page' => [... ]]; – 4k4 Apr 29 '18 at 16:23
  • This is it, thank you! Can you update you answer so I can accept it? – ptinca Apr 29 '18 at 17:09

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.