Finding url keyword or parent page id

Hi -

Up until now I’ve been using page ID’s to assign classes to the page body that I can then control in CSS (I am adjusting things like the background image depending on the website page). This is working fine except for any second level page that has multiple articles, so for example the projects page is find as I can just use the element ‘body.projects’ in my class, but for any projects articles this is an issue as the ID will be the name of the article.

<body class="<?= $page->uid() ?>">

Is there a way to find if the word ‘projects’ is used in the url and then assign the projects class or for any article page to assign the parent page id? Or another way around it that I’m not thinking of?

Thanks!

You can check for depth and then echo the parent’s UID:

<?php
if($page->depth() == 2) { echo $page->parent()->uid(); }
?>

Or, if you want to be independent of nesting depth:

<?php
if($page->depth() > 1) { echo $page->parents()->last()->uid(); }
?>

Thanks that’s a help. I’ve tried the following code and it’s working for the articles but no longer the parents. I’m doing something stupid no doubt…

<body class="<?php
if($page->depth() > 0) { echo $page->parent()->uid(); }
else echo $page->uid() ?>">

The lowest number is 1, so:

<body class="<?php e($page->depth() > 1,  $page->parent()->uid(), $page->uid()) ?>">

But note that this could have undesired results if the the page is nested several levels deep.

Thanks - I’ll only ever be 2 levels deep (or 1 depending how you count it) so it should be fine.

Spoke too soon - that won’t work for what I need to do! Is there a way to find a keyword or at least only apply it if the parent page is projects?

You can check if the page is a descendant of some other page: https://getkirby.com/docs/cheatsheet/page/is-descendant-of

Awesome! Exactly what i needed, thanks so much