Tech Blog :: Drupal trick: Embed a view anywhere with views_embed_view
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.
Google: TheBuckSt0p
Facebook: BenBuckman
LinkedIn
Github: newleafdigital
@thebuckst0p
Delicious: thebuckst0p
Drupal.org: thebuckst0p
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()orarg()to pull arguments from the URL, then pass them as an array toviews_embed_view.Post new comment
Don't bother putting in spam links. They'll be set to
rel=nofollowand will be removed and reported as spam shortly after submitting.