phpdrupal-7drupal-themingdrupal-templates

Drupal 7: Appropriate page template not loading


The path alias to the page is /annual-reports/2012. I have the following set up in the themes template.php file:

function tcm_preprocess_page(&$variables, $hook) {
    $alias = drupal_get_path_alias($_GET['q']);
    $alias = explode('/', $alias);
    $template_filename = 'page';
    foreach ($alias as $path_part) {
      if(is_numeric($path_part)){
          $variables['theme_hook_suggestions'][] = $template_filename . '__%';
      }
      $template_filename = $template_filename . '__' . $path_part;
      $variables['theme_hook_suggestions'][] = $template_filename;
    }
    print_r("<!--\n");
    print_r($variables['theme_hook_suggestions']);
    print_r("\n-->\n");
}

When I load the page it doesn't load the proper template. If you notice i'm outputting the suggestions array to comments to make sure the appropriate template is suggested. It outputs the following:

<!--
Array
(
    [0] => page__node
    [1] => page__node__%
    [2] => page__node__207
    [3] => page__annual-reports
    [4] => page__annual-reports__%
    [5] => page__annual-reports__2012
)

-->

I have a template file called page--annual-reports--%.tpl.php. It is however loading the base page--node.tpl.php. What am I missing?


Solution

  • Ok. The problem is ALL '-' characters need to be replaced with '_' in the template preprocessor, not just the ones between alias path parts. So the '-' between 'annual' and 'reports' had to be replaced also. So the for loop in my preprocessor looks like this now:

    foreach ($alias as $path_part) {
      if(is_numeric($path_part)){
        $variables['theme_hook_suggestions'][] = $template_filename . '__%';
      }
      $template_filename = $template_filename . '__' . preg_replace("/-/", "_", $path_part);
      $variables['theme_hook_suggestions'][] = $template_filename;
    }