6

What is the easiest way to select a template based on path alias. For example, if I have the following URLs:

http://www.example.com/mydirectory/page1
http://www.example.com/mydirectory/page2
http://www.example.com/mydirectory/page3

How would I go about creating a template for all of the pages in mydirectory? I should also add that using content type to theme these pages is not an option.

2 Answers 2

22

You can add some logic in a hook_preprocess_page() implementation that checks the alias, and adds theme hook suggestions if the path matches, e.g.

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

Then if you create a page--mycustomtemplate.tpl.php file in your theme, and clear the cache, any pages with an alias beginning mydirectory/ will use that new file instead of the standard page.tpl.php.

0
4

It's actually easier than that using drupal_match_path() which is how the blocks module works out whether a block should be displayed on a page or not:

function MYTHEME_preprocess_page(&$vars) {
  if (drupal_match_path(drupal_get_path_alias(), 'mydirectory/*')) {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}
0

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.