49

I want to theme the search result view mode with a template.

I had it in my head that naming a template file node--article--search-result.tpl.php would do the trick, but I'm obviously wrong about that.

I realise I can do node--article.tpl.php and within this check $view_mode, but this is awkward with all the other view modes that I don't want to template.

Ideas?

3 Answers 3

47

Adding theme hook suggestions in a node preprocess function should do the trick:

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'article' && $vars['view_mode'] == 'search_result') {
    $vars['theme_hook_suggestions'][] = 'node__article__search_result';
  }
}

After clearing the caches you should be able to use node--article--search-result.tpl.php for your template file name.

NB. You could also do this in your theme's template.php file by calling the function MYTHEME_preprocess_node() instead.

2
3

The Entity view modes module adds these template suggestions automatically

The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook_entity_info_alter() so they are available to any code that uses entity_get_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.

2

Here is a function that allows you to add new ones dynamically. It also calls the corresponding preprocess function if you have one declared.

Then call drush cache-clear theme-registry to get it working.

To use it replace THEME with your theme's name, and place it in your themes template.php file.

e.g. For a theme named Droid you would call it droid_preprocess_node(&$variables, $hook) {...

function THEME_preprocess_node(&$variables, $hook) {
  $view_mode = $variables['view_mode'];
  $content_type = $variables['type'];
  $variables['theme_hook_suggestions'][] = 'node__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'node__' . $view_mode . '_' . $content_type;

  $view_mode_preprocess = 'THEME_preprocess_node_' . $view_mode . '_' . $content_type;
  if (function_exists($view_mode_preprocess)) {
    $view_mode_preprocess($variables, $hook);
  }

  $view_mode_preprocess = 'THEME_preprocess_node_' . $view_mode;
  if (function_exists($view_mode_preprocess)) {
    $view_mode_preprocess($variables, $hook);
  }
}

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.