原文链接:https://www.drupal.org/node/1920746#utility
为了使Drupal8的主题尽可能的性能高并且允许更多的定制模板,请遵循以下这些最佳实践:
从预处理函数返回渲染数组
在模板中调用过滤器和功能函数
从预处理函数返回渲染数组
在预处理方法中返回渲染数组代替 theme() 或是 drupal_render().
Twig渲染自动渲染不需要调用drupal_render()或是theme()预处理函数。相反,渲染数组应该传到模板因为这允许得到更多已渲染的HTML字符串。
移除theme()预处理函数:
<?php
// Before - passing a string of rendered HTML to the template.
$variables['table'] = theme('table', array('header' => $header, 'rows' => $rows));
// After - passing a render array to the template.
$variables['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
);
?>
移除drupal_render()预处理函数是一个删除调用的问题:
<?php // Before, unnecessary call to drupal_render(). $variables['teaser'] = drupal_render($node_teaser); // After, with drupal_render() removed. $variables['teaser'] = $node_teaser; ?>
通常是drupal_render()加入数据的时候被调用.
<?php // Before, unnecessary call to drupal_render(). $row[] = drupal_render($display['title']); // After, with drupal_render() removed. $row[]['data'] = $display['title']; ?>
在模板中调用过滤器和控制函数
当渲染数组可寻址,可变数据的模板,不是所有的变量需要渲染数组。尽可能长时间的提供原始数据模板,主题开发应该调用过滤器例如t和控制函数例如Twig模板中的url().在Twig模板中调用预处理函数能够减少函数调用因为参数传到模板可能不在模板中显示。
以前:
在预处理函数中:
<?php
$variables['no_content_text'] = t('You have not created any content types yet. Go to the <a href="@create-content">content type creation page</a> to add a new content type.', array('@create-content' => url('admin/structure/types/add')));
?>
在模板中:
<p>{{ no_content_text }}</p>
以后:
在模板中:
<p>{{ 'You have not created any content types yet. Go to the <a href="@create-content">content type creation page</a> to add a new content type.'|t({'@create-content': url('admin/structure/types/add')}) }}</p>
显示/隐藏 & 移动 drupal_render_children 和 element_children
如果hide() 调用原始模板,drupal_render_children用于渲染“剩余”数据,我们需要将分离的变量进行预处理。
以前(php模板文件):
<?php hide($form['advanced']); hide($form['actions']); ?> <div class="layout-node-form clearfix"> <div class="layout-region layout-region-node-main"> <?php print drupal_render_children($form); ?> </div> <div class="layout-region layout-region-node-secondary"> <?php print render($form['advanced']); ?> </div> <div class="layout-region layout-region-node-footer"> <?php print render($form['actions']); ?> </div> </div>
预处理成分离的参数,传递给模板。你可能需要在呈现之前渲染变量全部元素。完全按照预期的展示模板。
以后:(预处理)
<?php
function template_preprocess_node_edit_form(&$variables) {
$form = $variables['form'];
// @todo Update this once drupal.org/node/1920886 is resolved.
$variables['advanced'] = $form['advanced'];
$variables['actions'] = $form['actions'];
unset($form['advanced'], $form['actions']);
$variables['form'] = drupal_render_children($form);
}
?>
以后:(Twig模板)
<div class="layout-node-form clearfix">
<div class="layout-region layout-region-node-main">
{{ form|without('advanced', 'actions') }}
</div>
<div class="layout-region layout-region-node-secondary">
{{ form.advanced }}
</div>
<div class="layout-region layout-region-node-footer">
{{ form.actions }}
</div>
</div>