What would be the best way for a module to insert a class into the body tag for all pages on a site?
I tried overriding the core page.tpl.php template in my module, but that caused an unrecoverable error. I had to tear the site down and rebuild it (it was a demo site).
Maybe I did that wrong? Any thoughts?
EDIT (August 16, 2024):
My use case for this is pretty specific and niche. I've created the Digital Agency Recipe Package, which creates a bunch of specific functionality and content in the way that a distribution might. I would like to provide a body class on all pages, when this recipe/module is active. It's my theory, that this will make it easier for another contributed theme to support this recipe. If there is a class specific to this recipe, other contributed themes can make modifications for this recipe without fear of breaking existing sites.
Comments
As usual with template files, the best way to add a class anywhere is to implement
template_preprocess_page(&$variables) {}
in your theme's template.php file (replacetemplate_preprocess_page
withYOUR_THEME_preprocess_page
).Then you simply do
I don't understand what is the need to have a body CSS class that is active on ALL pages on the site? If it's for every URL, then why you can't use CSS rules using the body tag itself as a selector.
But I've been trying to find a way for a long time and I would be very grateful if someone could tell me how to put a body class on certain categories of pages, for example:
Such a module existed for Drupal 6 and was extremely useful:
https://www.drupal.org/project/themer
The solution proposed by argiepiano can also be used - via template.php and not via a separate module, as long as if it is possible to code that generates a class differentiated at least for a specific NID TID or UID or just Random code for each page, layout or view
I was able to use the hint by @argiepiano in the .module file for my module. The code was this simple:
If you want to only add the class for a specific content type, wrap it in an "if" statement and check for whatever conditions you need.
Currently, Backdrop sets the body class only if the page is front page, class is "front", also for the content type - "node-type-page". It would be useful to have more additional classes depending on the specific content or View
Part of this work is done by the module
https://backdropcms.org/project/term_body_class
I've accomplished something similar by using a Paragraphs type with a class applied to it.
In page.tpl.php you can get the current path and add it to the class array
$classes[] = 'path-' . str_replace('/', '', $_SERVER['REQUEST_URI']);
You will get an original class for each page. Sometimes it helps.
@Enthusiast
Thanks so much for this tip!