Drupal 7 Adding a View or Block on page.tpl.php

mrroy69
mrroy69 used Ask the Experts™
on
Is it possible to render/display a view or a block on the page.tpl.php and then pass a value from the page url to the view/block to filter results based on the url value? Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Drupal Developer and Consultant
Commented:
I will assume the block is one that's been created in views since you're wanting to pass arguments to it.

First you'll want to retrieve your argument from the url using the arg() function. When viewing a page at the path "example.com/node/30", for example, arg(0) returns "node" and arg(1) returns "30". So let's say we want our node id from the second component of the path:
<?php $node_id = arg(1); ?>

Open in new window

Now let's say we have a view with a machine name of "my_view" which has a block display with a machine name of block_1 that accepts a contextual filter of a node id. You can see your machine names in the url when editing your block in the Views UI. We can embed the block and pass the $node_id we retrieved above as the argument for the contextual filter with the views_embed_view() function:
<?php print views_embed_view('my_view', 'block_1', $node_id); ?>

Open in new window

Place those two lines in your page.tpl.php wherever you want to render your views block. Also keep in mind that drupal gives you several variables to use in your page.tpl.php file. So, if the node id was really what you were after, you'd be better off using the existing $node variable that is already loaded. Then you could just use
<?php print views_embed_view('my_view', 'block_1', $node->nid); ?>

Open in new window

Author

Commented:
Thank you sir!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial