Drupal 6: can I pass variables to a node template by function call, not just by preprocess functions?
I'm working on a site for which I happen to need to embed the entire output of a node template (for a couple of content types) into various other templates. Most of the cases are embedding a node - selected in a nodereference CCK field - into a view template, so my current approach is:
- in the view settings: add the noderef field directly as one of the fields to output (as opposed to using a relationship to make the referenced node's fields accessible)
- set the format for field output to "full node" - which I've found prints the whole node template
This is great, BUT: there are a few important variables that are used in the node template. The only way I already know of to set these is via a preprocess function, which does work... The annoyance 开发者_如何学Gowith this method is that in the preprocess function I have to detect (by whatever is accessible there) where the template output will be embedded, so I can set the variables appropriately.
What I want to do instead:
Intuitively, it'd make way more sense to be able to call a function in my various view templates that would: a) allow me to print the whole node template, and b) pass in values for the preprocess variables. Does anyone know a function that can do this, or an alternate method?
[Thoughts so far that haven't gotten me anywhere:
I know in similar cases, you can pass in options as arguments to theme(), according to the signature of the particular theme function that will be called. But node_view() does not provide that ability -- and node_view() seems to be the proper function to call for invoking the node template, rather than theme('node', ...).
I see that node_view() invokes hook_nodeapi() with 'alter' as $op, but that is happening too late in the game; the node content will already be in HTML format by then (i.e. $node->body).]
Well, there is hook_nodeapi($op = 'view'), if you want to change existing elements, you give your module a high weight so that it is called last. To know when you want to customize something, you could set a custom flag on the node object, something like $node->yourmodule_inside_view_noderef = TRUE
before you pass it to node_view().
In Drupal 7, there is the so called $view_mode concept instead of just a boolean flag to show the teaser or not.
You can define your own view_modes through hook_entity_info(), here is an example from userpoints_nodeaccess: userpoints_nodeaccess_entity_info. This allows you to react based on the view_mode in hook_node_view/hook_node_view_alter but also allows you to customize which fields should be displayed how and which view_mode should be used when the node is displayed without needing custom code.
精彩评论