3

Trying to attach js by means of #attached by means of hook_page_alter (see https://drupal.stackexchange.com/questions/171918/how-to-add-javascript-with-attached-and-hook-page-alter), I found that the following code

 function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['content']['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

works properly - it attaches the file - while

function MODULE_page_alter(&$page) {
  $my_path = drupal_get_path('module', 'MODULE' );
  $page ['#attached']['js'][] = array(
    'js' => array(
    'type'=>'file',
    'data' => $my_path . '/module_test.js'),
  );
}

does not. Why is it so?

2

1 Answer 1

8

For #attached elements to be processed, the array needs to be run through drupal_render(). That never happens for the $page array.

Parts of it are rendered, e.g. in page.tpl.php:

<?php print render($page['content']); ?>

But never the $page array itself.

4
  • Are you sure? drupal_render_page() calls drupal_render($page).
    – donquixote
    Commented Sep 3, 2015 at 23:59
  • What difference does it make whether I call $page ['content']['#attached']['js'][] or $page ['header']['#attached']['js'][]?
    – Dalmaz
    Commented Sep 4, 2015 at 0:26
  • @donquixote hmm yeah you're right. Need to unpick that tomorrow, must sleep now. Dalmaz: it makes no appreciable difference really, assuming each is rendered it'll have the same effect
    – Clive
    Commented Sep 4, 2015 at 0:47
  • 1
    Yes, drupal_render_page() does go through the #attached js BUT it's too late that point. See drupal_render(). The drupal_process_attached($elements); call happens too late. The html.tpl.php is already rendered, so you can't affect the attached js/css, etc. Hat tip to my coworker.
    – jwal
    Commented Mar 8, 2018 at 0:18

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.