If based on template name?

Hey folks,

I’d like to add an if statement to a button that’s based on the template used, but I have no idea how to do it. At the moment I have:

<a class="button" href="<?= $child->buttonlink() ?>"><?= $child->buttontext() ?></a>

But what I’d like is for it to do the following:

IF the template="template1" THEN:
    <a class="button" href="<?= $child->url() ?>">Read <?= $child->firstname() ?>'s posts</a>
ELSE
    <a class="button" href="<?= $child->buttonlink() ?>"><?= $child->buttontext() ?></a>
ENDIF

I assume this is possible, and very simple, with a PHP if but I’m not great with PHP, and I’m still learning Kirby, so I’m struggling.

Thanks,

Kev

You can use intendedTemplate() for this

$page->intendedTemplate() | Kirby CMS.

<?php if($page->intendedTemplate()->name() === 'template1'): ?>
  <a class="button" href="<?= $child->url() ?>">Read <?= $child->firstname() ?>'s posts</a>
<?php else: ?>
  <a class="button" href="<?= $child->buttonlink() ?>"><?= $child->buttontext() ?></a>
<?php endif ?>

Be aware of the subtle difference with ->template() - that will return the final template … for example, Kirby witll fall back to the default template if the template you wanted does not exist.

Small fix, must be

if($page->intendedTemplate()->name() === 'template1')

Otherwise the strict comparison will fail, because $page->intendedTemplate() returns a template object, not a string.

Ah good spot, thanks :slight_smile:

Thanks both for this. I’m getting pretty close, but it’s not quite right. I have children of a page that have one of two templates - UpcomingPenpal or ActivePenpal, and I want the button to change based on this template. Here’s what I have currently:

<?php if($child->intendedTemplate()->name() === 'UpcomingPenpal'): ?>
        <a class="button" href="<?= $child->link() ?>">Visit <?= $child->firstname() ?>'s site →</a>
<?php else: ?>
        <a class="button" href="<?= $child->url() ?>">Read our conversation →</a>
<?php endif ?>

But all the buttons are being rendered with the “Read our conversation” part of the if, so it doesn’t seem to be matching the UpcomingPenpal template for some reason.

Thanks.

Just showing that the template name of the children is correct:

image

What does <?php dump($child->intendedTemplate()->name())?> tell you? Add that to the template outside the if statement.

How are you setting $child ? Do you actually have a UpcomingPenpal.php template in the templates folder?

The dump gave me the clue I needed, thanks! It wasn’t honouring the uppercase letters, so changing it to upcomingpenpal instead of UpcomingPenpal did the trick. Thank you so much!

The problem is probably due to uppercase use. Pleae never use uppercase chars in your template names (or snippets…).

While this might work in caseinsensitive environments, you are bound to run into troube if not.

Yeah, that’s exactly what it was, thanks. I’ve updated all the names and references to be lowercase.