In Drupal 7, it was possible to transfer attached elements such as css, javascript and http headers, from a render array to the page or response being processed by calling drupal_process_attached(). For example:
$build['#attached']['drupal_add_http_header'] = array(
array('Content-Type', 'application/rss+xml; charset=utf-8'),
);
drupal_process_attached($build);
return $build;
In Drupal 8, these attachments should now be left in the render array and will be automatically be handled at the appropriate time in the render pipeline.
$build['#attached']['drupal_add_http_header'] = array(
array('Content-Type', 'application/rss+xml; charset=utf-8'),
);
// No call to drupal_process_attached().
return $build;
If you do not have a render array to attach to because you're not altering a specific render element but rather the overall page, you can add them to the page by implementing hook_page_attachments() (Change notice):
function hook_page_attachments(array &$attachments) {
$attachments['#attached']['http_header'][] = array('Content-Type', 'application/rss+xml; charset=utf-8');
}
(Note that in this case, you must also specify the appropriate cacheability metadata to ensure it is only added on the appropriate pages.)
There are two other options for manipulating attached items:
- Use
attach_library()in a Twig template. - Set up an event subscriber for the
Symfony\Component\HttpKernel\KernelEvents::RESPONSEevent. SeeDrupal\Core\EventSubscriber\FinishResponseSubscriberfor an example. - Specify
$variables['#attached']in theme preprocess functions.
To render attachments without a controller, e.g. for tests, use the bare_html_page_renderer service.
The drupal_add_ or drupal_ prefix was dropped from the #attached keys in an earlier change, see https://www.drupal.org/node/2160069
See also this change notice regarding http header and status code generation: https://www.drupal.org/node/2549159
In addition, drupal_get_http_header() has been removed as part of this change. Per that function's earlier deprecation notice (also removed in the change), in Drupal 8 you should instead use: \Symfony\Component\HttpFoundation\Response->headers->get(). See also https://www.drupal.org/node/2181523.