Why does the theme layer uses render arrays when all the theming functionalities can be implemented with print
statements in templates files?
Is there any analogy that explains the use of render array in the theme layer and how it interacts with the template files?
2 Answers
Drupals render arrays are a great invention which make it possible to alter the output of content by others (modules, themes etc.).
If you would hard-code your output in variables to print, no one other can alter it. But if you use render arrays, then other modules can implement hooks to alter the rendering of your output if they need to do so.
For this flexibility it is best practice to use render arrays until the very last moment and let the twig template build the html from it.
-
1Yes. Think of it as telling the template what to output, while Drupal tells it “how” to render. If everything was printed as key/value as the OP asks, it would be a massive maintenance headache and kill all the interop/extensibility of theming.– KevinMar 9, 2019 at 17:21
A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type).
render($content['body']) contains everything in a structure in which the render function can turn it into display. This includes all your fields.
print $body[0]['value'] simply prints the value of that one field bypassing any rendering functionality such as "weight".
Rendering is a fun thing in Drupal, especially when you get to Drupal 7. Think of what you're passing into "render" as instructions on how to output, whereas the value is simply... a string... a value.
Nice documentation regarding Render Arrrays in Drupal 7 on Drupal.org
-
thanks mohit,but still i'm little bit confuse . Is render array contain key-value entries that is generated by node module only? or comments fields also included?– GiLLOct 16, 2012 at 13:34