Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

Template Questions /

giving a class to a section on a website


Reply


2 Posts   449 Views

Avatar
tee 1977

Community Member, 6 Posts

6 September 2012 at 10:00pm

Hi, im hoping someone out there can help me.

Basically i need to assign a different style class depending on the section you're on in the site and all its children pages need to follow this style. Normally if i wanted to assign a class to a page i would use body class="$URLSegment" etc. This is fine if you need one or two pages to look different but i need the parent and its children to follow the same class so i can color code text elements and it follows suit.

Im just scratching my head to find an easy solution.

many thanks

Tamara

Avatar
Willr

Forum Moderator, 5513 Posts

7 September 2012 at 9:34pm

Most of the time if I need section specific styles I'll add a new field on Page.php called 'Style' with that being configurable in the cms. Relaying on urlsegments is a little risky depending on the client!

class Page extends SiteTree {

static $db = array(
'Style' => 'Enum("Blue, Green, Red, Inherit", "Inherit");
);

function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Content.Main', new DropdownField('Style', 'Style', $this->dbObject('Style')->enumValues()));

return $fields;
}

function getPageStyle() {
if($this->Style == "Inherit") {
if($parent = $this->Parent()) {
return $parent->getPageStyle();
}
else {
return "Blue";
}
}

return $this->Style;
}

Then use $PageStyle in your template