You Are Here: Home » Articles » Digitizor » How-To » Programming » Tech

Drupal: How To Programmatically Add, Embed Or Insert Views In Your Theme tpl

By Debjit on December 3rd, 2010 
Advertisement

DrupliconThe Views module is one of the best things to have happened to Drupal. Views provides an easy way for any Drupal site designers to present how lists and tables of content. Views has a smart query builder that can build the proper query, execute it, and display the results. In this article we will tell you how to programmatically add, embed or insert Views in your theme's tpl. 

You can easily embed your pre-configured views in your theme's TPL using this command:

views_embed_view($name, $display_id = 'default')

This function is meant to be called from PHP snippets to embed a view in a Drupal node. It has two parameters: $name - The name of the view to embed and $display_id - The display id to embed. Consider this example below. We are embedding a view for displaying related articles after the article content type. For this we embed a view called Relatedarticles in our theme's  node-article.tpl.php file.

The code snippet below shows the scenario as explained above:

Drupal: Embed Views in your Theme

Drupal: Embed Views in your Theme

The snippet above shows a variable $display_id which is set to block_2. The illustration below shows how to find out the value for $display_id corresponding to the Display of the view that you want to embed in your website, progammatically.

Configure your views according to the Display IDs

Configure your views according to the Display IDs

The screenshot below shows the output of the view that has been embedded in the code snippet shown above, taken from oyestyle.com

Output of the programmatically embedded views

Output of the programmatically embedded views

The function views_embed_view won't display the title of the view. In order to get the title of the view, you can use the following code snippet:

$view = views_get_view($view_name);
print $view->get_title();

Should you require further help with the above "Programmatic View Embedding" or any other Drupal related problems then you can send us a mail with your query to: [email protected]

Advertisement







Drupal: How To Programmatically Add, Embed Or Insert Views In Your Theme tpl was originally published on Digitizor.com on December 2, 2010 - 1:28 am (Indian Standard Time)