Drupal 5包含了一个非常有用的机制,可以为不同的页面、区块、节点等提供不同的模板。例如,你可以为'blog'节点类型添加一个模板node-blog.tpl.php,从而取代默认的node.tpl.php模板。对于页面模板,就更加方便了,所以你可以为特定节点创建特定的模板,可参看基于当前路径适用不同的页面模板一文。
通过_phptemplate_variables()函数,还可以编辑可能的"template suggestions"(模板建议)列表。例如,下面的代码片断就基于URL别名创建了额外的“suggestions”(建议)。这比使用内部Drupal路径的方法更强大。
<?php
function _phptemplate_variables($hook, $vars = array()) {
switch ($hook) {
case 'page':
// Add node template suggestions based on the aliased path.
// For instance, if the current page has an alias of about/history/early,
// we'll have templates of:
// node_about_history_early.tpl.php
// node_about_history.tpl.php
// node_about.tpl.php
// Whichever is found first is the one that will be used.
if (module_exists('path')) {
$alias = drupal_get_path_alias($_GET['q']);
if ($alias != $_GET['q']) {
$suggestions = array();
$template_filename = 'node';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '_' . $path_part;
$suggestions[] = $template_filename;
}
}
$vars['template_files'] = $suggestions;
}
break;
}
return $vars;
}
?>