Alternativ menu title with fallback to regular title

Hello again! :wink:

I found out that I can introduce a new field for the menu title in the content.txt.

Menu: Alternativ title

----

Title: Regular title

----

Text: Lorem ipsum dolor sit amet, …

To get the alternative menu title I would use:

<?php echo $p->menu()->html() ?>

But which is the simplest and most elegant way to get the regular page title as menu title when the alternative title for the menu is missing in the content.txt?

Thanks in advance for your help!

I’d use the ternary operator:

<?php echo $p->menu()->isNotEmpty()? $p->menu()->html() : $p->title()->html() ?>
1 Like

Wow! Works very well, thank you very much! :+1:

Is this all PHP logic or more like a meta language to it? Unfortunately, I am still at the beginning when it comes to PHP. :innocent:

PS: I searched for ternary operator and learned something new! Thank you!

The syntax posted by @texnixe is natively supported by PHP. You can also use the following, which is a bit shorter but specific to Kirby:

<?php echo $p->menu()->or($p->title())->html() ?>
2 Likes

You just thaught me something here (again) !!

And I’ll be cheeky :yum:

<?= $p->menu()->or($p->title())->html() ?>
2 Likes

Looks slick! Thank you very much! :sunglasses:

PS: I hope I don’t annoy you with my newbie questions.

Not at all. You are very welcome. :slight_smile:

1 Like

Or with Kirby you can use like https://getkirby.com/docs/toolkit/api/helpers/ecco:

<?php ecco($p->menu()->isNotEmpty(), $p->menu()->html(), $p->title()->html()); ?>
1 Like

So many options. :wink:

2 Likes

The problem with using ecco() or its shorthand e() is that it “renders” the two options before evaluating which one to use. In your case, if menu is empty, you may get an error message as it calls html on a non object. I’ve ran into this before and was advised not to used ecco for those scenarii.

1 Like

For fields it’s fine (empty fields don’t cause errors), but it is correct that there are some situations where ecco does not work.
Please note that the ->or() syntax has these issues as well, but as I said, it is fine for fields.

2 Likes

Good to know thanks!