I understand I can hard-code this snippet into html.html.twig but i would prefer a cleaner method. My research is only instructing me how to attach libraries etc, but I can't find any example of injecting code into the header area needed by some third-party services.

I tried the following code, but it doesn't seem to work.

 * Implements hook_page_attachments().
function THEME_page_attachments(&$page) {
   * Initial JS.
  $javascript_header = "-----js code -----";

  $page['#attached']['html_head'][] = [
    // The data.
      // Add a <script> tag.
      '#tag' => 'script',
      // Add JavaScript to the <script> tag.
      '#value' => \Drupal\Core\Render\Markup::create($javascript_header),
      // Give weight so it appears after meta tags, etc.
      '#weight' => -1,


Your issue seems to be related with hook_page_attachments() not called from mytheme.theme file. If you look to the answer, it's written -

It appears that this function is only callable from a module, as it is listed in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module but not listed as a valid method in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

I verified with the current documentation & that's correct. You can use hook_page_attachments_alter, which has documented in above given document for Adding stylesheets and JS to a Drupal 8 theme.

  • Yes indeed. My code above works once I add alter to the function. Thank you. – drupalstrap Jan 18 '17 at 9:55
  • how to render the script tag within body tag? – Prerit Mohan Sep 14 '17 at 5:12

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.