3

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.

1 Answer 1

3

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().

3
  • 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? Commented Jan 20, 2022 at 16:17
  • 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.
    – 4uk4
    Commented Jan 20, 2022 at 17:13
  • Thanks, I've started another question for that part of the task, to keep things clearer. Commented Jan 20, 2022 at 18:13

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.