Adding class to <li> element if there is a child - subpage

Hi all,
I just started learning Kirby and developing a template with Tailwindcss and Alpine js , I got stuck when I tried to add a class to

  • element if there is a subpage? here is my code
    Any hep would be appreciated

    <ul class="flex grow flex-wrap items-center font-medium">
              <?php foreach($items as $item): ?>
                  <a href="<?= $item->url() ?>" class="text-gray-600 hover:text-gray-900 px-5 py-2 flex items-center transition duration-150 ease-in-out"><?= $item->title()->html() ?></a>
                  // get all children for the current menu items
                  $children = $item->children()->listed();
                  // display the submenu if children are available
                  if(! in_array($item->id(), ['blog']) && $children->isNotEmpty()):
                        class="origin-top-right absolute top-full left-0 w-40 bg-white shadow-lg py-2 ml-4 rounded"
                        x-transition:enter="transition ease-out duration-200 transform"
                        x-transition:enter-start="opacity-0 -translate-y-2"
                        x-transition:enter-end="opacity-100 translate-y-0"
                        x-transition:leave="transition ease-out duration-200"
                      <?php foreach($children as $child): ?>
                        <li><a href="<?= $child->url() ?>" class="text-sm text-gray-600 hover:text-teal-500 flex py-2 px-4 leading-tight" @focus="open = true" @focusout="open = false"><?= $child->title()->html() ?></a></li>
                      <?php endforeach ?>
                  <?php endif ?>
              <?php endforeach ?>
  • Where exactly do you want to add that class? You are already checking if there are children?

    Hi , sorry I forgot to mention :frowning: first main β€œli” element , what is the best way to check if there are child pages?
    Thank you

    You can use

    <li<?php if($item->hasChildren()) : > class="has-children"<?php endif; ?>>

    (see $page->hasChildren() | Kirby CMS)

    or, a bit less concise:

    <?php if($item->hasChildren()) : ?>
      <li class="hasChildren">
    <?php else : ?>
    <?php endif; ?>

    worked thank you , just missing β€œ?” :slight_smile: β€œ<?php if($item->hasChildren()) : >”

    Oops – I corrected it :wink:

    If it’s just about adding a class or not, the code could be shortened to

    <li <?php e($item->hasChildren(), 'class="hasChildren"', '') ?>>
    1 Like