Show fields (<?php echo $address['name'] ?><br /> …) only if the content is not empty

Hi,
I want to show my fields only if the content is not empty. This works so far with:

<?php if (!$page->textdetails()->empty()): ?>
    <div class="details">
        <?php echo $page->textdetails()->kirbytext() ?>
    </div>
<?php endif ?>

But how do I get it to work in this case:

Template:

<div class="address">
    <?php echo $address['name'] ?><br />
    <?php echo $address['job'] ?><br />
    <?php echo $address['phone'] ?><br />
</div>

Blueprint:

contact:
    label: Contact
    type: structure
    entry: >
      {{name}}<br />
      {{job}}<br />
      {{phone}}
    fields:
      name:
        label: Name
        type: text
      job:
        label: Job
        type: text
      phone:
        label: Phone
        type: text

I don´t know: Can the br tag be a problem?
When a field is not filled - the “br” breaks the line and leaves an empty line.

Does anyone have a solution?
Dan

You should be able to use something like this:

<div class="address">
    <?php if($address['name']):  ?><?php echo $address['name'] ?><br /><?php endif; ?>
    <?php if($address['job']):   ?><?php echo $address['job'] ?><br /><?php endif; ?>
    <?php if($address['phone']): ?><?php echo $address['phone'] ?><br /><?php endif; ?>
</div>

You can also use the toStructure() method instead of yaml() when parsing the structure field. This will allow you to use the syntax if(!$address->name()->empty()).

Hey Lukas,
the first version works perfectly. I will test your second approach.
Thanks a lot!

e is shorter: http://getkirby.com/docs/cheatsheet/helpers/e

<?php e($address['name'], $address['name']) ?>

and so on.

1 Like