I've got this working but it seems terribly verbose to do something, that in my opinion should be easier.

Is there a better way to get the assets from 2 different fields, merge them and output them in a random order?

{% set clientLogos = logos.clientLogos.all() %}
{% set agencyLogos = logos.agencyLogos.all() %}

{# set empty array #}
{% set logoIds = [] %}

{# add logos from clients #}
{% for logo in clientLogos %}
  {% set logoIds = logoIds|merge([logo.id]) %}
{% endfor %}

{#  add logos from agencies #}
{% for logo in agencyLogos %}
  {% set logoIds = logoIds|merge([logo.id]) %}
{% endfor %}

{# looped through merged logos #}
{% for logo in craft.assets().volume('uploads').kind('image').id(logoIds).orderBy('RAND()') %}
  <img src="{{ logo.url(croppedlogo) }}" alt="{{ logo.title }}" class="m-4"/>
{% endfor %}  

From Twig, this seems like a decent solution.

Could possibly be streamlined a bit if you wanted to do it from PHP, but as long as you're not dealing with large amounts of images, it's probably not worth it.

  • Is it possible to modify the query so that the resulting image array order respects that of the original arrays? (Eg client logos in order from the first array, then agency logos in order from the second array) – James Greig Apr 27 at 17:31

Assuming this is an entry page and you don't have other asset fields (though you could use targetElement), you could fetch assets relatedTo your current entry?

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.