1
{% set newsletterImages = newsletter.imagesCongratulations|merge(newsletter.imagesCis)|merge(newsletter.imagesSection3) %}
{% set transformedImages = newsletterImages %}

{% for image in newsletterImages %}
  {{ image.title }}<br />

{% endfor %}

newsletterImages is merging images from 3 different global fields. I want to then randomise and only output 6 of these images.

However, when I try

{% set transformedImages = newsletterImages.orderBy('RAND()').limit(6) %}

I get the error: Impossible to invoke a method ("orderBy") on an array. and Impossible to invoke a method ("limit") on an array.

Can anyone help point me in the right direction to achieve this?

2

You can achieve this with Craft's shuffle() method and Twig's slice filter (like you mentioned in your answer).

{% set newsletterImages = newsletter.imagesCongratulations.all() %}
{% set newsletterImages = newsletterImages | merge(newsletter.imagesCis.all()) %}
{% set newsletterImages = newsletterImages | merge(newsletter.imagesSection3.all()) %}

{% set shuffledImages = shuffle(newsletterImages) %}  // Shuffle our "master" array

{% for image in shuffledImages[:6] %}  // Get the first 6 images
  {{ image.title }}<br>
{% endfor %}
| improve this answer | |
  • Thanks Jalen. Just saw this after I updated my answer. But I prefer your naming approach :-) – Terry Upton Nov 6 '19 at 16:11
1

Here is the complete code that achieves what I want. In case it is useful to anyone else.

{% set newsletterImages = newsletter.imagesCongratulations.all() %}
{% set newsletterImages = newsletterImages | merge(newsletter.imagesCis.all()) %}
{% set newsletterImages = newsletterImages | merge(newsletter.imagesSection3.all()) %}

{% set shuffledImages = shuffle(newsletterImages) %}

{% set transformedImages = [] %}

{% for image in shuffledImages[:6] %}
  {% set transformedImage = craft.imager.transformImage(image, imageTransformParams) %}
  {% set transformedImages = transformedImages|merge([transformedImage]) %}
{% endfor %}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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