按节点类型覆盖html.tpl.php


17

在我主题的template.php文件中,我尝试了以下操作:

function media_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) 
  {
      // If the node type is "blog" the template suggestion will be "html--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'html__'.$vars['node']->type;

      // If the node type is "blog" the template suggestion will be "page--blog.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->type;

      // If the node id is "33" the template suggestion will be "page--33.tpl.php".
       $vars['theme_hook_suggestions'][] = 'page__'.$vars['node']->nid;    
  }

    //Create page suggestion for first part of url-alias
    $url_alias = drupal_get_path_alias($_GET['q']);
    $parts = explode('/', $url_alias);

    $vars['theme_hook_suggestions'][] = 'page__'.$parts[0].'__alias';  
}

这适用于page--nodetype.tpl.php,但不适用于html--nodetype.tpl.php

您可能会问为什么每个节点类型都需要覆盖html.tpl.php模板。这是因为我不想为此特定节点包括标记。

Answers:


28

预处理功能的名称基于正在处理的主题/模板。要预处理html.tpl.php文件,您需要使用hook_preprocess_html()

function media_preprocess_html(&$vars) {
  $node = menu_get_object();

  if ($node && $node->nid) {
    $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
  }
}

3

@Clive方法非常聪明。

还要注意,在html.tpl.php文件中,您可以从中读取要处理的内容类型$variables['classes'],这将给您类似html not-front not-logged-in no-sidebars page-node page-node- page-node-5638 node-type-CONTENT-TYPE-NAME

这样,您可以更改html.tpl.php文件的行为:

if (strpos($variables['classes'],'node-type-YOUR-CONTENT-TYPE') == true ) {
  echo 'Do something special  for YOUR-CONTENT-TYPE ';
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.