3

I'm using Drupal 7 to build a fairly simple directory site. I'm trying to theme my search results page the same as a taxonomy page, but as you may know, the results arrive by a completely different process in those two situations. I've copied the search-result.tpl.php file from the Search module to my own theme, and am trying to take advantage of the $result variable returned by the module. However, it doesn't seem to be as simple as print render($result);

I tried to isolate the relevant node object within $result and perform render() on it, like so:

$content=Array(); $content['#node'] = $result['node'];
print render($content);

But that just throws an error (can't use object as array) or simply returns nothing.

$result['node'] definitely contains the fields I want to echo on the page, so what am I doing wrong?

1 Answer 1

5

You need to prepare a view for the node object:

$view_mode = 'teaser'; // Or whatever
$view = node_view($result['node'], $view_mode);
print render($view);
6
  • Cheers, Clive! I ended up using field_attach_view('node', $node, 'teaser'). Is this a similar function? An alias? Is there a reason node_view would be better? Let me know and I'll happily update my code/accept your answer. Commented Feb 3, 2012 at 14:47
  • 1
    No problem :) I think node_view() would be better as it prepares the whole view for the node including running preprocess functions/templates etc. In fact if you look at node_view() it internally calls node_build_content() which in turn actually calls field_attach_prepare_view (and others), and invokes the entity_view hook for all modules. During that hook I believe field_attach_view() is called anyway
    – Clive
    Commented Feb 3, 2012 at 15:16
  • 1
    So I think the answer is, if you want the fully rendered/templated teaser node the use node_view(). If you just want the node content you should probably call node_build_content() and if you're just interested in the fields you should use field_attach_view(). Hope that makes sense :)
    – Clive
    Commented Feb 3, 2012 at 15:18
  • Yes, makes perfect sense to me. Commented Feb 3, 2012 at 15:44
  • By the way, I needed to say node_view($result['node'],'teaser') instead of simply naming a $view_mode variable. An edit might be in order. Commented Feb 3, 2012 at 15:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.