2

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,
    ],

    'key'
  ];
}
0

1 Answer 1

0

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.

2
  • Yes indeed. My code above works once I add alter to the function. Thank you. Commented Jan 18, 2017 at 9:55
  • how to render the script tag within body tag? Commented Sep 14, 2017 at 5:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.