preprocess

提供"可使用的 tpl 檔" Working with template suggestion

Preprocess function 的另一個少用但重要的功能就是提供 "可使用的 tpl 檔"

簡單點說明, Drupal 本身已經提供的 page-story.tpl.php 就是 temple_preprocess_page() 提供的
同樣, page-front.tpl.php 都是由 drupal 自帶的 temple_preprocess_page 提供

或者用 node.tpl.php 做例子,
Drupal 自帶的 template_preprocess_node() 提供 node-[nid].tpl.php 作為 "可使用的 tpl 檔"

當然, 我們的目的是提供一種 Drupal 沒有自帶的 tpl 命名方式,
例如另一種 content-type 的 tpl 命名: node-type-[type].tpl.php:

<?php
//mytheme 的 template.php 之內:
//1. 留意, 使用你自定的theme 的名稱
//2. 留意使用了 pass by reference 參數
function mytheme_preprocess_node(&$variables) {
 
$variables['template_files'][] =  'node-type-'.$variables['node']->type;
}
?>

$variables之內的變數可以參考 的提示

ref: Working with template suggestions http://drupal.org/node/223440

模版的預處理 template preprocess in Drupal 6.x

繼續 Drupal templates 的深度遊

Preprocess 是一個在你的theme 之內的 template.php 內的一組函數
用"一組" 的原因是因為一個theme 是可以有很多 preprocess function
正確來講, 一個 hook 便已經可以有10個 preprocess function (當然, 和 hook 一樣, 不用也是可以的)

而preprocess 的真正功用是,

  1. 為 templates 提供更多的變數以供使用
  2. 為hook 提供更多的template suggestion

第一點的功能很明顯, 因為 drupal 內建的 preprocess function (無錯, Drupal core 都是使用 preprocess 的)沒法為你的theme 的特殊性供你需要的變數
你便可以使用preprocess function:

<?php
//template.php 中提供一個 $foo_list 陣列
function yourtheme_preprocess_foo(&$vars) {
 
$vars['foo_list'] = array(
   
'list item 1',
   
'list item 2',
   
'list item 3',
  );
}

//sites/all/themes/yourtheme/foo.tpl.php 中便可以使用:
print $foo_list;
?>

待續 template suggestions......

ref:
preprocess functions http://drupal.org/node/223430

進階 views 模版(二): HTML 列表 Complex views templating, part 2, table, HTML list templates

part1

補一下 table 顯示之下的 theming.

假如你的 table 有4個 fields, views 的 theming information 便有6個 templates:
1個 display 的 tpl (page 或block)
1個 style tpl, 包含了 <table>
每1個 field 都可以有一個自己的 tpl (詳見 attachment)

HTML list (ul, ol) 也是同樣的情況
display + style tpl, 外加每個field 一個tpl
也可以做 field by field 的 tpl, 修改 <ul> 的class, <li>多個 span 之類

最後, 雖然和 views 無關, 但pager 也經常由 views 產生
但 views 的 pager 都是使用 core 的pager, theme_pager()
theme 的時候沒有 tpl, 要在 template.php 修改, 或者使用preprocess 提供 tpl