smartytemplate.php:你drupal主题的发动机

如果需要Drupal Smarty主题系统的高级特性的话,那么你需要在你的主题目录下面创建一个额外的文件(例如, e.g. themes/blumarine_smarty/smartytemplate.php).

 

这个文件可用来

  • 覆写主题函数,怎么覆写可参看phptemplate的: http://drupal.org/node/11811.
  • 为你的模板引入复杂的逻辑.
  • 方便的自定义函数或者修改已存在的函数,用于你的模板中.
  • 为你的模板定义额外的变量.

     

下面是一个覆写主题函数的例子:

(是从phptemplate中借鉴过来的)

 

首先你需要找到要覆写的主题函数的所在位置。你可以在Drupal API文档中找到一列这样的例子。在这里我们以theme_item_list()为例。

如果你要覆写的主题函数不包含在基本列表中(block, box, comment, node, page),你需要将它告诉给Smarty主题引擎.

为了实现这一点,你需要在你主题目录下,创建一个t smartytemplate.php文件.这个文件应该包含必须的<?php …?>标签,还有用于主题覆写的存根(stubs),这些存根告诉引擎使用哪个模板文件,以及向其中传递哪些参数.

 

theme_item_list()大概是这样定义的:

<?php
function theme_item_list($items = array(), $title = NULL, $type = 'ul') {
?>

现在,你需要在你主题的smartytemplate.php文件中加一个存根,如下所示:

<?php
/**
* Catch the theme_item_list function, and redirect through the template api
*/
function smarty_item_list($items = array(), $title = NULL, $type = 'ul') {
  // Pass to Smarty Theme Engine, translating the parameters to an associative array. The element names are the names that the variables
  // will be assigned within your template.
  return _smarty_callback('item_list', array('items' => $items, 'title' => $title, 'type' => $type));
}
?>

 

我们将函数名中的“theme”替换为了“smarty”,并调用函数_ smarty _callback()以将参数($items和$title)传递给Smarty主题引擎。

 

另外,在函数名中,除了'smarty'以外,你还可以使用主题的名字(例如,如果主题为bluemarine_smarty的话,那么bluemarine_smarty_item_list 和smarty_item_list都可以使用)。

 

现在,你可以在你主题目录下,创建一个item_list.tpl模板文件了,它将用来替代原有的theme_item_list()。这个函数,与原有的theme_item_list()相比,应该采用相同的逻辑。

 

有时,将显示委托给模板文件并不合适。如果直接使用php会更好的话,你在这里可以不用调用_smarty_callback(),而直接返回输出结果。

 

相关链接: http://drupal.org/node/70247 , Think in Drupal

Drupal版本: