Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Drupal - Render a View in a Node Template

Category: 

In this example, we have a content type called Unit (machine name: unit). And we want to programatically render a view on its node template. So we'll do something like this:

1. Create a copy of our theme's default node.tpl.php file and save it as node--[type].tpl.php file in your sites/all/themes/my_theme directory. In this example, a file name of node--unit.tpl.php is correct.

2. Render the view into a theme variable.

Inside your theme's template.php file, you'll need to implement template_preproccess_node (if it isn't already). The code would be something like this:

/**
 * Implements template_preproccess_node().
 */
function my_theme_preprocess_node (&$variables) {
  // Add variables so they are available in node--unit.tpl.php
  if ($variables['node']->type == "unit") {
        $variables['my_view_html'] = views_embed_view('my_view', 'default');
  }
}
3. Print the variable in the desired location within your node's template file. For this example, we would add this to the spot where we would like the view to be rendered inside node--unit.tpl.php:
<?php print $my_view_html; ?>

Add new comment