10

I don't completely understand when I should use hook_page_alter(&$page) or template_preprocess_page(&$vars, $hook) in Drupal 7.

What is the best practices about that to use in template.php?

Thanks

16

The difference is their purpose.

hook_page_build() and hook_page_alter() are used to remove, alter, or add elements at the page level.
The $page array passed to hook_page_alter() contains the top level elements for each block region. By default they are the following ones:

  • page_top
  • header
  • sidebar_first
  • content
  • sidebar_second
  • page_bottom

An example of implementation could be the following one:

function mymodule_page_alter(&$page) {
  // Add help text to the user login block.
  $page['sidebar_first']['user_login']['help'] = array(
    '#weight' => -10, 
    '#markup' => t('To post comments or add new content, you first have to log in.'),
  );
}

The preprocess functions are called to alter the variables that are passed to the template file. They cannot change the structure of the page, but they can alter the content of some elements of the page changing the content of those variables.
For example, the Overlay module removes the primary tabs when the page being visualized is the overlay.

function overlay_preprocess_page(&$variables) {
  if (overlay_get_mode() == 'child') {
    unset($variables['tabs']['#primary']);
  }
}
  • 1
    But with hook preprocess_page I can change the page structure by changing stuff inside $vars['page']. I use that because I had a hard time to get the nid with hook_page_alter for node page. – gagarine Jun 29 '11 at 20:34
  • 2
    You can get nid for a node page using menu_get_object() – andrewmacpherson Dec 16 '15 at 12:32

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.