在"body"中添加一个类

Chr*_*nch 33 drupal drupal-7 drupal-theming

如何修改或预处理<body>标记以添加类主体?我不想创建一个完整的html.tpl.php来添加一个类.

Cli*_*ive 52

在你的主题template.php文件中使用preprocess_html钩子:

function mytheme_preprocess_html(&$vars) {
  $vars['classes_array'][] = 'new-class';
}
Run Code Online (Sandbox Code Playgroud)

记住在实现钩子后清除缓存,或者Drupal不会拾取它.

  • 怎么知道添加到身体? (2认同)
  • `html.tpl.php`中只有一个元素添加了任何类,它是`<body>`元素; 上面的预处理函数适用于该文件,因此您添加的任何类只会添加到`<body>`元素中. (2认同)
  • @nikan可能现在有点晚了,但对于Omega你想实现`mytheme_alpha_preprocess_html`并将类添加到`$ vars ['attributes_array'] ['class']`数组 (2认同)

Pie*_*yle 9

html.tpl.php模板的文档将$classes变量记录为可用于通过CSS在上下文中设置样式的类的String..如果查看模板的代码,则此变量将用于生成的body元素的class属性中:

<body class="<?php print $classes; ?>" <?php print $attributes;?>>
Run Code Online (Sandbox Code Playgroud)

$classes实际上已经template_process()为任何模板文件设置了变量,并根据变量的内容进行构建$classes_array.

因此,要将一个类添加到页面主体,您应该将此类添加到$classes_array主题(或模块)的实现中的值hook_preprocess_html():

function THEME_preprocess_html(&$variables) {
  $variables['classes_array'][] = 'new-class';
}
Run Code Online (Sandbox Code Playgroud)

由于这是核心定义的模板和过程函数,任何行为良好的主题都应该重用相同的变量.


小智 5

我必须在同一个钩子中使用不同的数组键才能使其工作:

function THEME_preprocess_html(&$vars) {
  $vars['attributes_array']['class'][] = 'foo2';
}
Run Code Online (Sandbox Code Playgroud)