Drupal 8: #attached - Part 2

Blog Tags: Drupal 8, HTTP

If you have already gone through Drupal 8: #attached - Part 1, you’ve learned about the library, drupalSettings and http_header sub properties. If not, it’s highly recommended that you go back and learn about it first.

In this post, we will be learning about the following sub properties of #attached:

4. html_head_link


  • html_head_link is represented as $render_array[‘#attached’][‘html_head_link’]


  • Helps in creating <link> tags under HTML <head>.
  • In our routing callback, we have attached a link tag to the page which describes the author of the page.
  • Check the screenshot for reference:

5. html_head


  • html_head is represented as $render_array[‘#attached’][‘html_head’]


  • Helps in creating tags like <meta>, <style>, etc, under the HTML <head>.
  • In our routing callback, we have showcased the addition of a meta tag with the name ‘Cuisine’.
  • Check the screenshot for reference:


6. feed


  • feed is represented as $render_array[‘#attached’][‘feed’]


  • Feed is a special case of the html_head_link which creates <link> tags.
  • To demonstrate it, we have added a feed attachment in our render array which creates a link tag in the <head> section of the page.
  • Check the screenshot for reference:

7. placeholders


  • placeholders are represented as $render_array[‘#attached’][‘placeholders’]


  • Helps in adding placeholders to the markup which help in rendering complex markups late in the render process.
  • Firstly, In our render array we have created #markup which stores the placeholder called @foo.
  • Secondly, the placeholders key in #attached defines what markup the placeholder @foo represents.
  • Lastly, the markup in the UI will look like the screenshot below:

8. html_response_attachment_placeholders


  • These are represented as $render_array[‘#attached’][‘html_response_attachment_placeholders’]


  • Contain styles, scripts, scripts_bottom, and head placeholders which will help in sending static assets in the response before the markup requiring these assets. (This is automatically done by Drupal Core’s BigPipe module. For more details on this one, check out the BigPipe module.)

Closing Thoughts

In Drupal 7, we used different functions like drupal_add_css(), drupal_add_js(), drupal_add_html_head(), etc, for adding attachments. This was like remembering and calling different functions for different attachments.

On the other hand, as we saw above, Drupal 8 just uses the #attached property to add attachments to the HTTP response. That’s beautiful, right?

I hope this blog gave you new insights and a good introduction to render arrays in Drupal 8. :-)

In case you missed it, here's Part 1 of the Drupal 8: #attached series.