Tech Blog :: Drupal trick: Embed a view anywhere with views_embed_view


Jun 24 '10 11:20pm
Tags

Drupal trick: Embed a view anywhere with views_embed_view

I learned a new Drupal API function today: views_embed_view() to programmatically display a view inside another template (for example). Previously I had a custom function that loaded, executed, and rendered a view, several more lines of code than this.
I'm using it to pull a "Other Articles by Author" block into the side of a node template (the author is an argument):
echo views_embed_view('other_articles', 'block_1', $node->uid);
(Could also do the same in a preprocessor, $vars['other_articles'] = ...

For those who prefer not to write any code (and I've been increasingly impressed lately at Drupal designers who build amazing sites without any custom code), the Views Attach module (different from Views attachments) can pull Views into nodes. But for the code-inclined like myself, it can't be simpler than one line.

I'm curious of the pros/cons of the views_embed_view function vs views_attach or simply a view block. Are there performance considerations?

I have not always been able to get a view to work properly in a block when I need to get an argument from the URL. I like the concept of the views_embed_view() function but how do I pass that URL argument to the function?

I'm not sure what you mean. You can use menu_get_item() or arg() to pull arguments from the URL, then pass them as an array to views_embed_view.

Post new comment

Don't bother putting in spam links. They'll be set to rel=nofollow and will be removed and reported as spam shortly after submitting.

The content of this field is kept private and will not be shown publicly.
CAPTCHA
Are you human?