Using images inside structure field

Hi. For a project I’m working on I needed to add an image inside a structure field, that will then be available to the template. I used the following code to do this, but for some reason I think my solution is not very elegant and could be simpler. Any ideas?

Blueprint

publications:
    label: Publications
    type: structure
    fields:
        name:
            label: Name
            type: text
        info:
            label: Info
            type: text
        preview:
            label: Preview
            type: select
            options: images    
    width: 1/2 

Template

<?php $publications = yaml($page->publications()) ?>
<?php foreach($publications as $publication): ?>
    <div class="publication">
        <div class="name">
            <?php echo $publication['name'] ?><br />
        </div>
        <div class="info">
            <?php echo $publication['info'] ?>
        </div>
        <div class="preview">
            <?php $previewName = $publication['preview'] ?>
            <?php if ($previewName != ""): ?>
                <?php $previewUrl = $page->files()->find($previewName) ?>
                <?php echo $previewUrl->crop(400, 250) ?>
            <?php endif ?>
        </div>
    </div>
<?php endforeach ?>

Your code is perfectly alright. The only thing you could shorten is this line:

<?php $previewUrl = $page->files()->find($previewName) ?>

to

<?php $previewUrl = $page->file($previewName) ?>

Other than that, you could use the toStructure() method instead of the yaml() method.

Ah, good to know! Still your recommendations help as I’m trying to keep code as clean as possible. Thanks.

Just on a side note, you can also use chaining syntax instead of the brackets (was introduced a while ago and makes the code more coherent:

<?php $publications = $page->publications()->yaml() ?>
1 Like