Accessing Drupal Site Name and Menus in Templates

When I am creating a custom Drupal site, I like to hard code a few things into the templates, such as the site name and menus. This prevents the client from doing something like accidentally moving the menu blocks into a different region, and it also gives me more control over the HTML markup.

In Drupal 7, there are two ways that I have found to access this system data within the templates. I am going to walk through an example of each method in which I will add the following elements to my page.tpl.php template file:

  • My site name
  • The main menu
  • A custom menu named “Secondary menu” (which has a machine name of “menu-secondary-menu”)

Method 1

The first method involves setting up some variables in the template.php file and then accessing those variables in the page.tpl.php file.

In the template.php file:

function newhopeks_preprocess_page(&$variables) {
    $variables['site_name'] = filter_xss_admin(variable_get('site_name', 'Default Site Name'));
    $variables['main_menu'] = menu_main_menu();
    $variables['secondary_menu'] = menu_navigation_links('menu-secondary-menu');
}

In the page.tpl.php file:

<h1><?php print $site_name; ?></h1>
<?php
    print theme('links__system_main_menu', array('links' => $main_menu));
    print theme('links__menu_secondary_menu', array('links' => $secondary_menu));
?>

Method 2

The second method bypasses the template.php file and accesses the data directly.

In the page.tpl.php file:

<h1><?php print filter_xss_admin(variable_get('site_name', 'Default Site Name')); ?></h1>
<?php
    print theme('links__system_main_menu', array('links' => menu_main_menu()));
    print theme('links__menu_secondary_menu', array('links' => menu_navigation_links('menu-secondary-menu')));
?>

Related Resources