Rendering Drupal Views in code

Having a query builder like Views at your fingertips is fantastic on so many levels. I'm not going to get into my deep and semi-weird love affair with Views at this point in time, but I will show you how to programmatically display your Views display in code. This can be useful in a custom module, perhaps in a hook_node_view or maybe in one of your node or page templates.

In this example I'll add my View to my blog nodes. I'll just append my View to the bottom of the blog content. We'll want to use the views_embed_view() function to render our desired View display.

/**
* Implementation of hook_node_view().
*/
function deckfifty_node_view($node, $view_mode, $langcode) {
  if($node->type == 'blog' && $view_mode == 'full') {
    $node->content['body'][0]['#markup'] .= views_embed_view('campaigns');
}

As you can see, the first parameter is the machine name of the View, in this case: campaigns. The default for the second parameter is the "default" display. So if you want to enter a different display it'll look something like this:

views_embed_view('campaigns', 'block_1');

Again, this is the machine name of the display. We can go one step further - if the View has an argument you would like to pass, this can be done with the third parameter. In my View I've added a Node: nid argument (or should I say Contextual Filter!). If I wanted to pass an arbitrary nid to the View, it can be done like this:

views_embed_view('campaigns', 'block_1' , 20);

Now the results of my View will only have the contents of node 20. While this isn't a very dynamic or exciting example you can see the power of this function and hopefully it will find its way in your Drupal developer toolbox for a future project!