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!

2
  • 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. Commented Apr 29, 2018 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. Commented Apr 29, 2018 at 14:16

1 Answer 1

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().

4
  • 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)" Commented Apr 29, 2018 at 14:45
  • The error was my mistake, sorry. Disregard the above comment. But I'm still not getting attachments. Commented Apr 29, 2018 at 14:49
  • I think you need to enclose the page in an html render element to attach libraries: $build = ['#type' => 'html', 'page' => [... ]]; Commented Apr 29, 2018 at 16:23
  • This is it, thank you! Can you update you answer so I can accept it? Commented Apr 29, 2018 at 17:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.