0

this function caches the output, so it doesnt work if I want to change dynamically between two template files. For example user-profile.tpl.php and user-profile-project.tpl.php

Code:

function hook_theme_registry_alter(&$theme_registry) {
  $tmp1 = arg(0);
  $tmp2 = arg(1);
  $tmp3 = arg(2);

  if ($tmp1 == "user" && is_numeric($tmp2) && !$tmp3) {
    $user = user_load($tmp2);
    $roles = $user->roles;
    if (in_array('project', $roles)) {
     $theme_registry['user_profile']['template'] = 'user-profile-project';
    }
  }
}

So how can I do this differently?

1

Implement hook_user_profile_preprocess() and add your template suggestion as last entry of $variables['theme_hook_suggestions']. Instead of using arg() as you are doing, use menu_get_object('user', 1).

hook_theme_registry_alter() is not good because:

  • Drupal caches what it gets from hook_theme_registry_alter()

      // _theme_registry_build()
      if ($cached = cache_get('theme_registry:build:modules')) {
        $cache = $cached->data;
      }
    
  • It is never invoked for each page request Drupal gets; so you could not for which user the user profile is.

Then, the Drupal way would probably be to check the user has a specific permission rather than a specific role.

if ($account = menu_get_object('user', 1) && user_access('your permission', $account)) {
  $variables['theme_hook_suggestions'][] = 'your template suggestion';
}

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.