[Drupal 7] How to add a template file to theme a view inside your custom module?

| | 2 min read

You may be familiar with the theme information link in views. The theme information link in view tells us which files are to be modified, to theme the view. You could get more information regarding the view from, http://viewshelp.doc.logrus.com/help/views/analyze-theme. This is the case where we have a theme with us. But what if you don't have a theme and you still want to theme the view's result? Well, read on if you want to find out how to theme a view by adding a template file inside your custom module.

The steps to be followed are:

  1. Create the template file and place it inside the module folder.
  2. Implement hook_theme inside your module

You can implement hook_theme like:

function modulename_theme($existing, $type, $theme, $path) {
  return array (
    'base hook_displayname' => array (
      'variables' => array('view' => NULL, ['options' => NULL, 'rows' => NULL, 'title' => NULL]),
      'template' => //provide the name of the template file ,
      'base hook' => // provide the name of the base hook,
      'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

base_hook.png

Suppose your theme information is as above.

If you want to theme the display output, then your 'base hook' is 'views-view'. Create a tpl with name views-view-table--list-customers--page.tpl.php. The above code can be changed in to

function modulename_theme($existing, $type, $theme, $path) {
  return array (
    'views_view__list_customers__page' => array (
      'variables' => array('view' => NULL,),
      'template' => 'views-view--list-customers--page' ,
      'base hook' => 'views_view',
      'path' => drupal_get_path('module', 'modulename'),
    ),
  );
}

If you want to theme the style output, then your 'base hook' is ' views-view-table'. The above code can be changed in to

function modulename_theme($existing, $type, $theme, $path) {
  return array (
    'views_view_table__list_customers__page' => array (
      'variables' => array('view' => NULL, 'options' => NULL, 'rows' => NULL, 'title' => NULL),
      'template' => 'views-view-table--list-customers--page' ,
      'base hook' => 'views_view_table',
      'path' => drupal_get_path('module', 'modulename'),
    ),
  ); 
}

The above example can be used for the other formats of view as well. You may require to clear the cache to get it work.
Hope this helps!!!