1

We are using a masonry grid, with 3 image sizes (different heights). The images are (one of) the banner image(s) from the news entries. We played around with this, however this doesn't work as we need to limit the image output - per entry - to only one. Running on the latest Craft 3 version.

How can we, randomly, have one out of three image transforms, applied to the banner image of each entry?

This is the code:

{% block content %}
    <div class="content">
        <div class="grid-items js-isotope js-grid-items">
            {% for entry in craft.entries.section('news').limit(10).all()  %}
            {% set image = entry.bannerImage.one() %}
            <div class="grid-item js-isotope-item js-grid-item">
                <div class="card">
                    <div class="item"><img alt=""  src="{{ image.getUrl( 'masonryLarge' )}}"/></div>
                    <div class="card-block">
                        <div class="card-posted"><a href="#">{{ entry.author }}</a> on {{ entry.postDate | date('M d, Y') }}</div>
                        <h4 class="card-title">{{ entry.title }}</h4>
                        <div class="card-text">Lorem ipsum dolor sit amet, consect etur adipiscing elit. Mauris vel auctorol est. Integer nunc ipsum...</div>
                        <a href="{{ entry.url }}" class="card-read-more">Continue</a>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
{% endblock %}

The transforms are: masonryLarge, masonryMedium & masonrySmall

1 Answer 1

3

You can use Twigs Random function

{{ random(['masonryLarge', 'masonryMedium', 'masonrySmall']) }} 

So you could do something like

{% for entry in craft.entries.section('news').limit(10).all()  %}
    {% set image = entry.bannerImage.one() %}
    <div class="grid-item js-isotope-item js-grid-item">
        <div class="card">
            <div class="item"><img alt=""  src="{{ image.getUrl( random(['masonryLarge', 'masonryMedium', 'masonrySmall']) )}}"/></div>
            <div class="card-block">
                <div class="card-posted"><a href="#">{{ entry.author }}</a> on {{ entry.postDate | date('M d, Y') }}</div>
                <h4 class="card-title">{{ entry.title }}</h4>
                <div class="card-text">Lorem ipsum dolor sit amet, consect etur adipiscing elit. Mauris vel auctorol est. Integer nunc ipsum...</div>
                <a href="{{ entry.url }}" class="card-read-more">Continue</a>
            </div>
        </div>
    </div>
{% endfor %}

Or you can use Twigs Cycle function

{% for entry in craft.entries.section('news').limit(10).all()  %}
    {% set transform = cycle(['masonryLarge', 'masonryMedium', 'masonrySmall'], loop.index0) %}
{% endfor %}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.