我如何修改或预处理标签以添加类名为“body”? 我不想创建整个html.tpl.php文件来添加一个类。
在你的主题的template.php
文件中使用preprocess_html
钩子:
function mytheme_preprocess_html(&$vars) {
$vars['classes_array'][] = 'new-class';
}
一旦你实现了钩子,记得清除缓存,否则 Drupal 将无法检测到它。
html.tpl.php模板的文档将$classes
变量记录为可用于通过CSS上下文样式化的类字符串。如果查看模板代码,此变量将用于生成的body元素的class属性中:
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
$classes
变量实际上已经由 template_process()
设置在任何模板文件中,其内容从 $classes_array
变量中构建而来。hook_preprocess_html()
,并将这个类添加到 $classes_array
的值中。function THEME_preprocess_html(&$variables) {
$variables['classes_array'][] = 'new-class';
}
由于这是核心定义的模板和处理函数,任何良好的主题都应该重复使用相同的变量。
function THEME_preprocess_html(&$vars) {
$vars['attributes_array']['class'][] = 'foo2';
}
Common Body Class 模块通过一个界面为用户提供了向任何页面添加类的功能。该界面具有选择多个用户角色以及可以呈现类的页面的选项。
attributes_array
是Omega主题特定定义的。对于“普通”的主题,它将是classes_array
。 - Clive我在别人建的网站上应用了这个技术。起初它没有起作用,但后来深入挖掘发现 $classes 变量没有在 tpl 文件中输出。所以如果它不起作用,请检查一下。
这是一种简单的方法,可以根据URL添加基于类的内容,适用于Drupal 9。无需启用模块。
/**
* Implements hook_preprocess_html().
*/
function THEME_NAME_preprocess_html(&$variables) {
// Get the current path
$current_path = \Drupal::service('path.current')->getPath();
$internal_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
// Assign it to body class
$variables['attributes']['class'][] = str_replace("/", "", $internal_path);
}
参考:http://www.thirstysix.com/how-can-i-add-body-class-based-path-page-specific-class-drupal-9
html.tpl.php
文件中只有一个元素添加了任何类,即<body>
元素;上面的预处理函数是针对该文件的,因此您添加的任何类都将仅添加到<body>
元素。 - Clivedpm
函数;它将呈现出放置在通常消息区域中的类和数组的漂亮表示形式...这是调试的绝对必备工具。例如,您可以在上面的函数中像这样使用它:dpm($vars);
,它会将数组打印到屏幕上,以便您进行检查。 - Clivemytheme_alpha_preprocess_html
并将类添加到$vars['attributes_array']['class']
数组中。 - Clive