Last updated March 8, 2009. Created by owahab on February 10, 2006.
Edited by rootwork, ashtonium, merlinofchaos, puregin. Log in to edit this page.

If you are investigating the use of the Views module, and would possibly like to embed content from a view into regular node content, there are a couple contributed modules that can help you out:

  • The Insert View module acts as a filter in Drupal that can be enabled for various input methods.
  • The Viewfield module adds on a field type for your CCK nodes, and allows you to select the desired view.

A more advanced option is to embed a View by hand with PHP. This can be done in the node edit page (if you are using an input method with the PHP evaluator filter enabled) or via PHPTemplate in your theme's .tpl.php files.

First, we would use views_get_view($view_name) to create a view object, then we'd use views_build_view($type, &$view, $args = array(), $use_pager = false, $limit = 0, $page = 0) to display it. Note: both of these functions are provided in views.module, please see that file for additional usage documentation.

Basically, all that views_build_view requires is a type value (we'll be using 'embed') and a view object. The optional variables include an array of views arguments, an option to output the view in pages, how many results to return (or how many results to return per page), and which of the returned pages to start on.

As a simple example, I can edit a node and embed a view into it with the following code:

<?php
//load the view by name
$view = views_get_view('sample_view');
//output the view
print views_build_view('embed', $view);
?>

As a more complex example, let's assume that I want to embed a view on all nodes of a specific type but have different results returned based on the node's title. One way to do this would be to place the following code in your node-type.tpl.php file:

<?php
//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);
?>

You can also build a view in different ways:

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.
result
Return an $info array. The array contains:
  • query: The actual query ran.
  • countquery: The count query that would be run if limiting was required.
  • summary: True if an argument was missing and a summary was generated.
  • level: What level the missing argument was at.
  • result: Database object you can use db_fetch_object on.
items
Return info array as above, except instead of result, items: An array of objects containing the results of the query.
queries
Returns an array, summarizing the queries, but does not run them.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

The two modules provide slightly different methods for admins to allow a user with node-edit permission to select any view to include in their node as content.

  1. Insert View Module enables a tag which can be used inline in the body of any node of any type. (I assume - please correct me if that's inaccurate)
  2. View Field Module requires CCK and adds a field which admins may include in any content type. It manifests on the node-edit tab as a selection list of available views, and appends the selected view to the node body. (A similar effect to - but easier interface than - using code in an 'input PHP' field to append a view,
  3. The PHPtemplate method, however, is important if admins don't want node-editors to be able to change which view is displayed. When the code is inserted into a node_$type.tpl.php, node.tpl.php, or template.php, the view is defined for that content type, and becomes part of the content-type's structure. It cannot be changed by users no matter what permissions they have been granted. An example of this would be the homepage for a drupal module (eg http://drupal.org/project/viewfield). Imagine this is a nodetype 'project' and the table is a view of 'issue' nodetypes associated with that project.

The Innovating Tomorrow blog had a post recently about yet another method, using the theme() function.

function smart_blockview($myview, $mylimit, $mytype, $mytitle) {
// $myview is the view name
// $mylimit is the number of items
// $mytype can be block, page or embed
// $mytitle is the block title we declare here because we want it to print only view exists
// GET_TERM_ID_FORVIEWS
$termcheck = strstr($_GET['q'], 'term/');
$termID = str_replace('term/','', $termcheck);
if (is_numeric($termID)) {
$view_name = $myview; //name of view
$view = views_get_view($view_name);
if ($view) {
//GETVIEW
$title = $mytitle; // title of the block
$limit = $mylimit; // number of returns
$type = $mytype; // number of returns
$view_args = array($termID);
// PRINTVIEW
      $output = '<div id="smart_blockview_'. $view_name .'">';
      $output = '<h2 class="view_block_title">';
$output .= $title;
$output .= "</h2>\n";
$output .= views_build_view($type, $view, $view_args, FALSE, $limit);
$output .= "</div>\n";
return $output;
} /* end if view */
} /* end if is_numeric */
}

for template php.. change mytheme with your theme name
then
<?php
echo smart_blockview(featured_product, 2, block, 'Featured Product');
?>

create block and add function call from php input
...
well.. and thats the view you create
$view = new stdClass();
  $view->name = 'featured_product';
  $view->description = '';
  $view->access = array (
);
  $view->view_args_php = '';
  $view->page = FALSE;
  $view->page_title = '';
  $view->page_header = '';
  $view->page_header_format = '3';
  $view->page_footer = '';
  $view->page_footer_format = '3';
  $view->page_empty = '';
  $view->page_empty_format = '3';
  $view->page_type = 'node';
  $view->url = '';
  $view->use_pager = TRUE;
  $view->nodes_per_page = '30';
  $view->block = TRUE;
  $view->block_title = '';
  $view->block_header = '';
  $view->block_header_format = '3';
  $view->block_footer = '';
  $view->block_footer_format = '3';
  $view->block_empty = '';
  $view->block_empty_format = '3';
  $view->block_type = 'node';
  $view->nodes_per_block = '5';
  $view->block_more = FALSE;
  $view->block_use_page_header = FALSE;
  $view->block_use_page_footer = FALSE;
  $view->block_use_page_empty = FALSE;
  $view->sort = array (
  );
  $view->argument = array (
    array (
      'type' => 'taxid',
      'argdefault' => '1',
      'title' => '%1',
      'options' => '1',
      'wildcard' => '',
      'wildcard_substitution' => '',
    ),
  );
  $view->field = array (
    array (
      'tablename' => 'node',
      'field' => 'title',
      'label' => '',
      'handler' => 'views_handler_field_nodelink',
      'options' => 'link',
    ),
  );
  $view->filter = array (
    array (
      'tablename' => 'uc_products',
      'field' => 'is_product',
      'operator' => '=',
      'options' => '',
      'value' => '1',
    ),
  );
  $view->exposed_filter = array (
  );
  $view->requires = array(node, uc_products);
  $views[$view->name] = $view;

Have Fun! :)

I want to dispaly views in my texonomy.term.tpl.php file. I follow your steps,
I have add function smart_blockview in my templete.php rename it with project2welve_blockview
then I have I call that function in texonomy.term.tpl.php file. Please reply me whats wrong with me?

Thanks,
Gajanan

<?php
//load the view by name
$view = views_get_view('sample_view');
//output the view
print views_build_view('embed', $view);
?>

Fatal error: Call to undefined function views_build_view() blah blah blah \includes\common.inc(1685) : eval()'d code on line 5

My bad, I was running 6 and didn't read the posts above. I apologize and will go back to the corner, where's my dunce cap.

<?php
$view
= views_get_view('viewname');
print
$view->execute_display('default', $args);
?>

This is how you do it in Drupal 7
<?php echo views_embed_view('view-name', $display_id = 'display-name') ?>

"display-name" is the name of the particular display from that view you want to embed.

An example would be:

<?php echo views_embed_view('users_registered', $display_id = 'volunteers_list') ?>

--
Carlos Miranda Levy
Civil Innovation Lab
NEVER HELP: engage, enable, empower and connect...
www.civ.do www.relief20.com www.socinfo.com
www.educar.org www.bibliotecasvirtuales.com
www.haitird.com www.civila.com

So where do you stick this PHP code in Drupal 7? In a custom module? Theme? Or some hidden PHP snippet?

In the template

I am a newbie and i've been looking for the last 2 days at a way to generate a dynamic view.

What i want to accomplish: From a category view page where i have all my articles displayed, when the user clicks on one of the articles, instead of going to the article node, to take him to a custom article view.

Where i am today: Till now i thought that it has to be someway that from the category view to get a dynamic generated article view but i can't find:

  • how from category view to pass (post) the unique id to the article view
  • how from article view to take (get) the unique id and render the appropriate content.

How you can help me:

  • Tell me if the way i was thinking is possible to implement. (no need for the actual "how to do it" a yes or no will suffice and i'll keep looking)
  • Can you show a larger snippet of code where that "echo views_embed_view" should go?
  • If you know a good source where i can find a overall structure of how categories and articles should be "looked at" in drupal. Theoretical structure

Many thanks.

Drupal version: 7

This comment above worked for me out of the box in a node.tpl.php for embedding a view. Thank you for posting.

In a taxonomy-term.tpl.php I couldn't get a result though using the code for displaying a view in a theme template.

Turned out I had to pass an additional parameter for the contextual filter that was set in the view.

<?php echo views_embed_view('view-name', $display_id = 'display-name', $conditional_arg1) ?>

An example for a taxonomy term page would be:

<?php echo views_embed_view('foods', $display_id = 'fruits', $tid) ?>

Where $tid would be the term id of the term for apples, oranges, or pears for example. So let's say you build a view named foods with a content pane named fruits that shows the nodes for all the nodes labeled with a fruit kind.
If apples has a term id of 1, when you visit /taxonomy/term/1, then it would show a listing of nodes that have a taxonomy term apples attached.

Dear :
Q1.
if i have a view ,maine_mane='view_X'.
and,this view have 4 page ,machine name is p1,p2,p3,p4

In general,I add a UI Tabs for show this view by tabs. It's OK.

No,I want let this view show by tabs format ,and be embed on node.

<?php echo views_embed_view('view_X', $display_id =      ) ?>

Q2.
<?php echo views_embed_view('foods', $display_id = 'fruits', $tid) ?>
how to set argument in view or noed ,to recive or get argument?

thx