Nav item with children is listed twice

Hi there,

I am building up a main navigation with Kirby 2. Could you please help out - as soon as an item has children, I want to list them and name the title of their parent item as the clickeable item. The problem is that the items with children are listed twice. First standalone, then with TITLE. Here is my code. It is based upon https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_responsive_navbar_dropdown.

<div class="topnav" id="myTopnav">
  <?php foreach($pages->visible()->not('aktuelles') as $item): ?>
  <a href="<?= $item->url() ?>"><?= $item->title()->html() ?></a>
  
  <?php if($item->hasVisibleChildren()): ?>
    <div class="dropdown">
      <button class="dropbtn">TITLE<i class="fa fa-caret-down"></i></button>
    <div class="dropdown-content">
      <?php foreach($item->children()->visible() as $item): ?>
        <a href="<?php echo $item->url() ?>"><?php echo $item->title()->html() ?></a>
      <?php endforeach ?>
    </div>
    </div>
  <?php endif ?>
  <?php endforeach ?>
  <a href="<?php echo $pages->find('aktuelles')->url() ?>"><?php echo $pages->find('aktuelles')->title()->html() ?></a>
  <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
</div>

You have to turn the logic round and use if-else:

<div class="topnav" id="myTopnav">
  <?php foreach($pages->visible()->not('aktuelles') as $item): ?>
 
  <?php if($item->hasVisibleChildren()): ?>
    <div class="dropdown">
      <button class="dropbtn">TITLE<i class="fa fa-caret-down"></i></button>
    <div class="dropdown-content">
      <?php foreach($item->children()->visible() as $item): ?>
        <a href="<?php echo $item->url() ?>"><?php echo $item->title()->html() ?></a>
      <?php endforeach ?>
    </div>
    </div>
  <?php else: ?>
    <a href="<?= $item->url() ?>"><?= $item->title()->html() ?></a>
  <?php endif ?>
  <?php endforeach ?>
  <a href="<?php echo $pages->find('aktuelles')->url() ?>"><?php echo $pages->find('aktuelles')->title()->html() ?></a>
  <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a>
</div>

Works perfectly. Thank you so much, Sonja!

2 Likes