Best way to link to a page in a Template

Trumpets playing!!! Yes. Brilliant.

I’ll try it now

… Assuming a page with id newsletter actually exists in the content root folder.

1 Like

Yep. Works as expected.

THANK YOU

I hate to be a PITA and I know it makes stuff more complicated, and I am repeating myself eternally, but to prevent errors in case the page doesn’t exist or is later renamed, this should be:

<?php if ($p = page('newsletter'): ?>
  <a href="<?= $p->url() ?>">Subscribe to newsletter</a>
<?php endif ?>

@Mark_E In your case, if you have no intention of ever renaming your page, moving it anywhere, or deleting it, you can leave the code as is. Just posting this here for the rest of the world.

1 Like

Thanks. No I don’t think I’ll ever rename, move or delete the page – and if I did I’d tweak the link… but I can see that working on a client’s site this would be something to consider.

So the following code/link will still work even if a client moved the page (say made it a child page) or renamed the page? That’s clever!

<?php if ($p = page('newsletter'): ?>
  <a href="<?= $p->url() ?>">Subscribe to newsletter</a>
<?php endif ?>

From my own experiments I believe if the page doesn’t exist, or has been deleted, the link is not displayed.

No, but it will prevent that an error is thrown if the page doesn’t exist.

Yes, the link is not shown.

No, but it will prevent that an error is thrown if the page doesn’t exist.

By not displaying the link at all?

Yes, why would you want a link to something that doesn’t exist? If you still wanted an empty link to show up, you could also do it like this:

<a href="<?= ($p = page('newsletter')) ? $p->url(): '' ?>">Subscribe to newsletter</a>

Or if you are on PHP 8.0+, using the so-called “null-safe operator” (PHP null-safe and null-coalescing operators - DEV Community):

<a href="<?= page('newsletter')?->url() ?>">Subscribe to newsletter</a>

Thanks for clarifying what happens if a link is broken.

I’ve been using the following code, in a PHP snippet, to link to a page.

<a href="<?= page('ethical-design')->url() ?>">

This works fine, on parent and child pages.

But I’d like to link to an anchor on the ‘ethical-design’ page. I tried:

<a href="<?= page('ethical-design#eco')->url() ?>">

But I now get a PHP error in the browser. Is it possible to link to an anchor link on a page?

The page helper expects a page id/uuid as attribute, so you cannot simply add something to this, as it will result in null, and then you cannot call url() on null. So you have to use string concatenation and add the hash to the url:

<a href="<?= page('ethical-design)->url() . '#eco' ?>">
1 Like

Thanks.