Thursday, September 30, 2010

Drupal 6: How to Embed a View Into a Template

For Drupal: If you need to embed a view inside a template file, a few lines of code is what you need. Lets take a look at the first solution based on the manual:


//load the view by name
$view = views_get_view('faq_topics');
//output the top three items in the view with the node title as an argument
print views_build_view('embed', $view, array($title), false, 3);

There were three issues involved in this code:

  • This code is logic. In keeping with the separation of layers this would violate that by bringing logic into the presentation layer.

  • What if views changes the way that views works. If views changes this means there is some work to do with changing your code. And, more places this could happen with two functions being called. This may seem small, and it is, but it's something to consider.

  • Something about this seems that you should be able to do this in one function. If this is the standard way for modules and themes to embed views why have two functions to do it.


Here is a better way of doing it, via a Views function called theme_view:

print theme('view', 'faq_topics', 3, false, 'embed', array($title));

This would display the same thing as the code above. But, it's theme code and it's one function.
The arguments for this function are:

theme('view', $view_name, $limit = NULL, $use_pager = NULL, $type = 'embed', $view_args = array())

The documentation of the arguments:

/**
* Returns a themed view.
* @param $view_name
* The name of the view.
* @param $limit
* Maximum number of nodes displayed on one page. if $limit is set and $use_pager is
* not, this will be the maximum number of records returned. This is ignored
* if using a view set to return a random result.
* If NULL, the setting defined for the $view will be used.
* @param $use_pager
* If set, use a pager. Set this to the pager id you want it to use if you
* plan on using multiple pagers on a page. Note that the pager element id
* will be decremented in order to have the IDs start at 0.
* If NULL, the setting defined for the $view will be used.
* @param $type
* 'page' -- Produce output as a page, sent through theme.
* The only real difference between this and block is that
* a page uses drupal_set_title to change the page title.
* 'block' -- Produce output as a block, sent through theme.
* 'embed' -- Use this if you want to embed a view onto another page,
* and don't want any block or page specific things to happen to it.
* @param $view_args
* An array containing the arguments for the view
*/

Source: http://www.innovatingtomorrow.net/2007/12/09/how-embed-view

1 comment: