Drupal – chaging the content of $node through hook_node_view

Drupal has hooks, one of then is called hook_node_view which allows you to inject variables into your node templates. In order to actually modify the node with the content variables… done like so:

[php]
$node->content[‘variable’] = ‘new var’;
[/php]

You need to actually return the $node variable from the hook function.

[php]
//mymodule.module
function mymodule_node_view($node, $view_mode, $langcod){
if($node->type == ‘content_type’){

$node->content[‘variable’] = ‘new var’;
return $node;
}

}
[/php]

You can then use the variable in your node template.

[php]
//node–content-type.tpl.php
print $content[‘variable’];

[/php]

Published on: 27 June 2014
Posted by: Sami K.