Score:2

What is the difference/purpose of 'content' and 'elements' keys, in preprocess?

jp flag

I'm using hook_preprocess_node and looking at $variables. I can see there's two similar keys: content and elements. I see that there's a comment in the core code:

  // Helpful $content variable for templates.

next to code that copies all elements keys into content... I'm unsure why it's helpful, how it's different, and when one would use elements or content to achieve a particular goal.

This is a general question, but my task at hand is that I have two separate taxonomy term reference fields and I wish to combine them, alphabetically by term name, into one list for presentation.

Score:2
cn flag

elements is the variable name defined in theme_hook() to hold the renderable elements (for the node this is the entity build array). Preprocess is then responsible to prepare variables for rendering, like content.

If your goal is to modify the template output then check first which variables are actually printed. In a node template it doesn't make sense to change elements in preprocess, any changes you make will be discarded. You can however do this in the build process, for example in hook_entity_view_alter().

jp flag
So the *node* module generates a render array with all the node's data in render arrays under `'elements'`. Then `template_preprocess_node()` sets defaults for the node, which is where the whole *copy `elements` to `content`* comes from. So this means `elements` is only left there "just in case" (?) but that in terms of continuing the render process, `content` is what now matters. Is that about right?
4uk4 avatar
cn flag
Yes, but in your case you might want to change the build array before it reaches the preprocess hook. This looks more like you want to alter the build array, not to theme the output.
jp flag
Thanks, I've started [another question](https://drupal.stackexchange.com/questions/309299/render-two-taxonomy-fields-in-one-alphabetical-list/309300#309300) for that part of the task, to keep things clearer.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.