Conditional (If) statements within structure

Hi there! Essentially what I’m after is that if there is a link in the structure field I want to display the word ‘(link)’ and link out to that URL. If there is no link in the structure field then I don’t want it to display anything. I’m pretty sure the solution I’m looking for is using an if statement or an e() statement? I am very new to Kirby so any help would be greatly appreciated! At the moment I can get the link to display using echo but if there is no link in the panel it still displays the text :sweat:

    <?php foreach ($page->press()->yaml() as $item): ?>
    <ul>
      <li><i><?php echo $item["title"];?></i>, <?php echo $item["publication"];?>, <a href="<?php echo $item["link"];?>">(link)</a></li>
     </ul>
 <?php endforeach ?>

It’s a bit easier with toStructure()

<ul>
    <?php foreach ($page->press()->toStructure() as $item): ?>

      <?php if ($item->link()->isNotEmpty()): ?>
      <li>
          <i><?= $item->title();?></i>, 
          <?= $item->publication() ;?>, 
          <a href="<?= $item->link();?>">(link)</a>
      </li>
      <?php endif ?>

 <?php endforeach ?>
</ul>

Your ul element has to be outside. the foreach loop, btw. Otherwise you. create a new list for each link.

If you only don’t want to. show the link, then. put the if statement around the a. tag.

1 Like

You can just use common PHP controll structures.

<ul>
    <?php foreach ($page->press()->yaml() as $item): ?>
  <li>
    <i><?php echo $item["title"]; ?></i>, <?php echo $item["publication"]; ?>
      <?php if ($item["link"]): ?>
        ,<a href="<?php echo $item["link"]; ?>">(link)</a>
      <?php endif; ?>
  </li>
 <?php endforeach ?>
</ul>
1 Like

Amazing! Thanks so much for your help. toStructure() seems like a better solution.

I still wanted to display the title and publication but omit the link if there was no link in the panel. So I moved the line <?php if ($item->link()->isNotEmpty()): ?> to after the title and publication variables and it’s working now. Thanks again!

  <ul>
    <?php foreach ($page->press()->toStructure() as $item): ?>
      <li>
        <i><?= $item->title();?></i>,
        <?= $item->publication() ;?>
        <?php if ($item->link()->isNotEmpty()): ?>
        <a href="<?= $item->link();?>">(link)</a>
      </li>
      <?php endif ?>

    <?php endforeach ?>
  </ul>