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.
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?
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?
Thanks for your reply! You pointed me in the right direction. I've added the following solution to my templates.
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.
$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.
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.