8

We are constantly improving our coding performance and we are monitoring every page load to optimize loading en rendering times in our websites.
Above statement in mind, I stumbled upon the question where should we render the renderable arrays?

If you render them in your preprocessor, the template keeps pretty neat since you're only printing variables.

Preprocessor:

function template_preprocess_node__faq(&$variables) {
    $node = node_load($variables['nid']);
    $node_style = node_view($node, $variables['view_mode']);

    $faq_sets = array(
      '#theme'  => 'my_module_faq_set',
      '#sets'   => $variables['field_faq_set'],
    );

    $variables['faq_image']   = render($node_style['field_faq_image']);
}

Template:

<div class="faq_image">
     <?php print $faq_image; ?>
</div>

However, I'm not sure it this is the proper/fastest/neatest way to preprocess and print variables.

Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

Does anyone have a rule and/or some tips and advices on how to tackle this issue the cleanest and fastest way?

  • 2
    This question is rather subjective. The general rule is that computing is done in the preprocess function and the rendering in the template file. It's not clear why you are using node_view() to render a field; fields are not rendered that way in a node template. – kiamlaluno Apr 28 '15 at 7:11
  • Thanks for the info. Then why is Drupal rendering in the node.tpl.php and printing in html.tpl.php? How would you tackle the node_view() issue? – Michiel Apr 28 '15 at 7:17
7

Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

That's not quite right. If you look at template_preprocess_html() you can see that nothing is run through render()/drupal_render(). So quite simply the variables in html.tpl.php are printed rather than rendered because they don't need to be rendered. All the vars are already strings, and no render arrays were used to build the template.

Conversely, the node content in node.tpl.php is a render array. So any parts of it that need to be rendered have to be run through render() and not just printed.

I would be tempted to follow core's example of using render() in templates, not in preprocess functions, unless you have a specific reason to do it differently.

From a performance point of view the difference would surely be negligible, but profiling the code in the context of your site and hardware is the only way to be certain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.