Loop, template and spaghetti code

Hi,

I would like to clean up the template below, but I don’t know how.
Can someone point me in the right direction?

I have a list of pages with a “related” select field in the panel that may point to another section (archive, in this case).
Inside the parent template, I need to know if the select field is filled, if the page exists and finally to access the data (url, title, …).

This is the home template:

<div class="carousel">
  <?php foreach($page->children()->visible() as $item): ?>
    <div class="carousel-cell">

      <!-- ugly, help me -->
      <?php
        if($item->related()->isNotempty()) {

          $relatedPage = $pages
                         ->filterBy('template', 'archive')
                         ->children()
                         ->findBy('uid', $item->related());

          if($relatedPage != null) {
            $related = $relatedPage;
          } else {
            $related = false;
          }
        }
      ?>
      <!-- ugly -->

      <?php if($related): ?>
        Things
      <?php endif ?>">

    </div><!-- carousel-cell -->
  <?php endforeach ?>
</div><!--carousel -->

And this is the blueprint of home-item:

title: Home item

preview: parent

fields:
  title:
    label: Title
    type:  text

  text:
    label: Text
    type: textarea

  related:
    label: Related
    type: select 
    options: query
    query:
      page: archive
      fetch: children
      value: '{{uid}}'
      text: '{{title}}'

Thank you! :sunny:

I’d store the URI of the related page instead of the UID, then in your template:


<div class="carousel">
  <?php foreach($page->children()->visible() as $item): ?>
    <div class="carousel-cell">

      <?php if($relatedPage = $item->related()->toPage()): ?>
        <?= $relatedPage->title(); // and other stuff ?>
      <?php endif ?>

    </div><!-- carousel-cell -->
  <?php endforeach ?>
</div><!--carousel -->

If you don’t want to change your blueprint and what is already stored in your items:

<div class="carousel">
  <?php foreach($page->children()->visible() as $item): ?>
    <div class="carousel-cell">

      <?php if($relatedPage = page('archive')->children()->findBy('uid', $item->related())): ?>
        <?= $relatedPage->title(); // and other stuff ?>
      <?php endif ?>

    </div><!-- carousel-cell -->
  <?php endforeach ?>
</div><!--carousel -->
1 Like

The result is definitely better in both cases, and storing the URI instead of the UID is a good idea.
Thank you.