1

I wanted to add a piece of HTML at the top of all pages, right after <body>. In the #drupal IRC channel I got the recommendation to override html.tpl.php in the theme. That works fine. But isn't there some useful hook that I could use, so I don't have to copy html.tpl.php and just add a few lines?

I tried to modify $variables['page']['page_top'] in THEME_preprocess_page() and THEME_preprocess_html() but upon debugging $page_top in html.tpl.php, the changes had been discarded.

How do I do it by hook? And which way is to prefer?

1
  • 1
    Hook will probably use more time than a simple, static change to one tpl file. And why copy it? Most themes needs to have it anyway, already, so all you need is to alter it.
    – Mołot
    Jul 23, 2014 at 14:33

3 Answers 3

1

Have a look at how the Drupal core toolbar module does this:

/**
 * Implements hook_page_build().
 *
 * Add admin toolbar to the page_top region automatically.
 */
function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

This is probably the most correct way of adding something to the page top as you can comfortably use render arrays.

0

$page_top is rendered in template_process_html(). You should be able to override that function to add material before it is rendered and assigned to $variable

2
  • I interpreted this as implementing THEME_process_html(), but when I did that I had rendered HTML to deal with. That is actually fine in my case because I can just prepend my HTML to $variables['page_top']. But I'm still wondering where the opportunity is to modify the render array (and that is what your answer really seems to be about - am I misunderstanding it?).
    – Arla
    Jul 24, 2014 at 7:17
  • As per the link I provided, the function does the following: $variables['page_top'] = drupal_render($variables['page']['page_top']); where the array is rendered. It also states at the very top of the page, "To customize these variables, call drupal_render() on elements in $variables['page'] during THEME_preprocess_page()"
    – Geoff
    Jul 24, 2014 at 12:28
0

You can add region page_top in your_theme.info file, see reference Writing theme .info files
The other way is to change html.tpl.php file in your theme, but the first way is better.

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.