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?

 

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 (replace template_preprocess_page with YOUR_THEME_preprocess_page).

Then you simply do

$variables['classes'][] = 'my-new-class';

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:

  • Path - a class to be active only for a given page or more specifically NID (for nodes), TID (for tags) and UID (for users)
  • Content type - for all nodes of a specific content type
  • User Role
  • Random

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

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