Hello,
it is possible to add a custom css class to a page from backend?
Like:
Home <-- main
Contact <-- sub
Hello,
it is possible to add a custom css class to a page from backend?
Like:
Home <-- main
Contact <-- sub
Yes, it is possible. You can do this by using the $page->template()
function. If you do not have a custom template, you could instead use the $page->uid()
function.
Here’s a basic example on how to achieve this:
<?php
if ( $page->template() == 'contact' ) {
$class = 'sub';
} else {
$class = 'main';
}
?>
<main class="<?php echo $class ?>">
Your content.
</main>
https://getkirby.com/docs/cheatsheet/page/uid
https://getkirby.com/docs/cheatsheet/page/template
Edit: Sorry, I was using the wrong function. My mistake for not checking my code before posting I have corrected the code and function.
If you don’t want to use the template, but have individual classes for your pages, you can also use the page UID, or the value of any field of your pages.
Do you have a snippet?
this could work, i think…
*Wondering about the fast response in this community.
<main class="<?= $page->uid() ?>">
Your content.
</main>
There is one caveat to using any of these solutions: If the UID or the template is changed, the css class is worthless. For those pages where having a class is crucial, make sure to disallow temlate/UID change or use a read only field in your files.
Just a tiny typo
<main class="<?= $page->uid() ?>">
Your content.
</main>
I use something similar (i’m also outputing the template name) but on my root element instead
<html class="<?= $page->uid() ?>">
@JimmyRittenborg oops, yes, thanks, I have corrected it above.