dynamically add class to element depending on page url

Permalink
Rookie question here. I have all my content wrapped in a div.ccm-page, followed by a <main> element. I'd like to add a class to this element to reflect the page I'm on.

Example:http://localhost/concrete5project/index.php/projects... is called and a class named "projects" is added to the <main> element of the page template (<main class="projects">).

Got this working rather clumsily with the below code.

$urlSegments = explode('/', $_SERVER['REQUEST_URI']);
   $activePage = basename($_SERVER['PHP_SELF'], ".php");
   $mainClass;
   if ($activePage == 'index') {
      $mainClass = $activePage;
   } else {
      $mainClass = $urlSegments[3];
   }
<main class="<?php echo $mainClass; ?>">


The reason I'm doing this is because I want to be able to target specific pages with CSS/LESS. I figure there must be a smarter or more c5-specific way. How is everyone else doing this?

 
ob7dev replied on at Permalink Best Answer Reply
ob7dev
So if your theme code has a div called .ccm-page that wraps everything, if you wanted another class that is specific to the page your on, you could do something like:
class="ccm-page page-<?php echo $c->cID?>"

So if your on the home page, the classname would be page-1, and whatever the unique ID of the page your on, thats what will be added as a classname.
publicb replied on at Permalink Reply
Thanks for your reply! You pointed me in the right direction. I've added the following solution to my templates.

$page = Page::getCurrentPage();
$activePageName = strtolower($page->getCollectionName());
<main class="<?php echo $activePageName ?>">


I have a page with a page/topic list and the nice thing about this is that it returns the value I want, even if the page list is filtered and the URL looks likehttp://localhost/c5project/index.php/projects/topic/7/project_topic... In which case it returns 'projects' and adds it to the element, which is what I was looking for.

This website stores cookies on your computer. These cookies are used to improve your website experience and provide more personalized services to you, both on this website and through other media. To find out more about the cookies we use, see our Privacy Policy.