2

I am using this function on a D7 site to template based on url alias and everything works except when a page has a dash in it. For example mysite.com/test-page doesn't work. I tried page--test-page.tpl.php and no luck. If I change to testpage and use page--testpage.tpl.php it works. Any ideas?

Here is the function that works:

function mytheme_preprocess_page(&$variables) {
    // Get the alias for the page being viewed
    $alias = drupal_get_path_alias($_GET['q']);
    if ($alias != $_GET['q']) {
        $template_filename = 'page';

        //Break it down for each piece of the alias path
        foreach (explode('/', $alias) as $path_part) {
            $template_filename = $template_filename . '__' . $path_part;
            $variables['theme_hook_suggestions'][] = $template_filename;
        }
    }
}
2

Found solution here: http://cheekymonkeymedia.ca/blog/gene-bernier/how-create-page-tpl-suggestions-based-path-alias-drupal-7

Here is what I used to fix the dash in titles error. I also added no node-content-type solution:

function mytheme_preprocess_page(&$variables) {
  // Get the alias for the page being viewed
  $alias = drupal_get_path_alias($_GET['q']);
  if ($alias != $_GET['q']) {
    $template_filename = 'page';
    //Break it down for each piece of the alias path
    foreach (explode('/', $alias) as $path_part) {
      // Added the str_replace becayse path parts with - were not being picked up properly by the theme_hook_suggestions
      $template_filename = $template_filename . '__' . str_replace("-", "_", $path_part);
      $variables['theme_hook_suggestions'][] = $template_filename;
    }
  }

  if (isset($variables['node'])) {
    // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
    $variables['theme_hook_suggestions'][] = 'page__'. $variables['node']->type;
  }
}
0

hyphens in template file names are important to Drupal. I can't think of a reason why your template doesn't work, because in my experience it probably should.

However, rather than trying to make that work, why not eliminate the hyphens?

$variables['theme_hook_suggestions'][] = str_replace(str_replace("-", "", $template_filename);

now you can use "page--testpage.tpl.php", which is a file name that Drupal can make sense of.

edit: if you're worried about collisions, replace "-" with something alphanumeric.

  • Nope. Doesn't work. Strange. I am not sure why my above doesn't work? – HanSoloShotFirst Feb 12 '14 at 19:18

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.