By admin |

drupal 7 模版文件templates.php的一点使用经验及小结

1:在drupal里面,page.tpl.php默认是没有根据content type来定制模版的。如果想根据content type定制模版怎么办?很简单。
找到当前主题下的template.php文件。一般的主题都有。如果没有,请创建。加入下面的代码:  

function THEMENAME_preprocess_page(&$variables, $hook) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    $variables['theme_hook_suggestions'][] = 'page__type__' . $node->type;
  }
}

注意一下,一定要用下划线。

写完,新建一个page--type--yourtype.tpl.php文件,就可以使用这个模版来控制yourtype的输出了。 

2:我想在page.tpl.php文件里面使用$submitted变量,而且这个变量可使用自定义格式。 

function dzhy_preprocess_page(&$variables, $hook) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    $user = user_load($node->uid);
    $variables['submitted']  = '文章作者:' . $user->field_alias['und'][0]['value'] . '    ' . date('Y-m-d h:i:s',$node->created);
  }
}
运行完上面代码,然后到page.tpl.php里面

 试试。当然上面的field_alias要变成你自己的东西。。。 

 3:引申使用,比如我想在page.tpl.php里面,echo $hello,打印出 ‘hello world!';请看下面的代码片段。 

function dzhy_preprocess_page(&$variables, $hook) {
    $variables['hello']  = 'hello world';
}

  到你的page.tpl.php里面,echo $hello试试。 

 4:分享一个刚刚领悟出来的模板模式,就是根据根据用户是否登陆,呈现不同的模版方式。代码如下: 

function dzhy_preprocess_node(&$vars,$hook){
  global $user;
  if($user->uid>0 && $vars['type'] == 'qa'){
    $vars['theme_hook_suggestions'][] = 'node';
  }elseif($user->uid==0 && $vars['type'] == 'qa'){
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'];
  }
}

 说到现在,你应该有点明白了吧?