Docs > Examples > Setting page style based on context

In this example, the page background colour depends on how the page has been categorised. The category can be set from the page location, or using page metadata.
To keep it simple, let's suppose a page has a blue background if it's a news story, or a green background otherwise. The CSS looks like this:
body { background-color:green; }
body.news { background-color:blue; }
First, let's suppose that a "news story" is one that appears in a root-level section named "News". Then we could code the <body> tag of the web template like this:
<body class="{page.path.substr(0, page.path.indexOf('/'))}">
For a page in, say the section "news/uk/technology", this would become:
<body class="news">
while for a page in "company/about-us", it would become:
<body class="company">
For a more complex case, it will be better to create a variable and set its value depending on context. The above example would become:
<?js var bodyclass = page.path.substr(0, page.path.indexOf('/')); ?>
<body class="{bodyclass}">
Now, suppose any page that is based on the "News article" template is also a news story, regardess of what section it is in. We could write:
<?js
var bodyclass;
if (page.template=='News article') {
bodyclass = 'news';
} else {
bodyclass = page.substr(0, page.indexOf('/'));
}
?>

<body class="{bodyclass}">
To take a different tack, let's suppose the "Standard article" template includes a metadata flag to indicate whether or not the page is a news story. A <content:boolean> tag written in the <head> of the template will be displayed as a checkbox in the metadata tab of the Page Editor. Here's what the template code looks like:
<html>
<head>
<content:base/>
<content:boolean id="is-news"/>
</head>

<?js
if (page.getText('is-news')=='true') {
bodyclass = 'news';
} else {
bodyclass = 'standard';
}
?>

<body class="{bodyclass}">
...
</body>
</html>


Can't find what you're looking for?

Let us know and we'll see if we can help.