How can I modify or pre-process the <body>
tag to add the class body? I don't want to create a whole html.tpl.php just to add a class.
We used the add() method to add a class on the body object. We can access the body element on the document object. If the class is already present on the body element, it won't get added twice. You can pass as many classes to the add() method as necessary.
HTML. Using . add() method: This method is used to add a class name to the selected element.
In your theme's template.php
file use the preprocess_html
hook:
function mytheme_preprocess_html(&$vars) { $vars['classes_array'][] = 'new-class'; }
Remember to clear the caches once you've implemented the hook or Drupal won't pick it up.
The documentation for the html.tpl.php template documents the $classes
variables as String of classes that can be used to style contextually through CSS.. If you look at the code for the template, this variable is used in the class attributes of the produced body element:
<body class="<?php print $classes; ?>" <?php print $attributes;?>>
The $classes
variables is actually already set by template_process()
for any template file and build from the content of the $classes_array
variable.
So to add a class to the body of your page, you should add this class to the $classes_array
value from your theme (or module)'s implementation of hook_preprocess_html()
:
function THEME_preprocess_html(&$variables) { $variables['classes_array'][] = 'new-class'; }
Since this is the core defined template and process function, any well-behaving theme should re-use the same variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With