<p>This is how you do it in case anyone is looking for this.</p>

<pre><code>{% set assets = craft.assets.limit(null) %}

{% set randomEntry = craft.entries.section('homes').order('RAND()').relatedTo({
    targetElement: assets,
    field: 'homeImages'
}) %}

{% for homesEntry in randomEntry.limit(6) %}
    {% set asset = homesEntry.homeImages.first() %}

    {% if asset %}
        &lt;a href="{{ homesEntry.url }}"&gt;&lt;img src="{{ asset.url('galleryImages') }}" alt="{{ asset.title }}"&gt;&lt;/a&gt;
    {% endif %}
{% endfor %}
</code></pre>

CC BY-SA 3.0
2015-07-21T13:56:46.550Z
2015-07-21T16:06:05.430Z
2015-07-21T16:06:05.430Z
Bryan Garrant
<p>How can I limit the output of assets based on this criteria?</p>

<ol>
<li>search all entries randomly in section "homes" for only entries with at least one asset image</li>
<li>limit those results to 8 random assets</li>
</ol>

<p>I tried this but it does not always show exactly 8 asset images as the random is called first:</p>

<pre><code>{% set assets = craft.assets.limit(null) %}

{% for homesEntry in craft.entries.section('homes').limit(8).order('RAND()') %}
    {% if homesEntry.homeImages|length %}
        {% set asset = homesEntry.homeImages.first() %}

        {% if asset %}
            &lt;a href="{{ homesEntry.url }}"&gt;&lt;img src="{{ asset.url('homeImages') }}" alt="{{ asset.title }}"&gt;&lt;/a&gt;
        {% endif %}
    {% endif %}
{% endfor %}
</code></pre>

<p>Any help is appreciated.</p>

<assets><limit><random>
How can I limit the output of assets randomly if an asset exists?
# How can I limit the output of assets randomly if an asset exists?

(Asked by: username_0 on 2015-07-21)

How can I limit the output of assets based on this criteria?

search all entries randomly in section "homes" for only entries with at least one asset image
limit those results to 8 random assets

I tried this but it does not always show exactly 8 asset images as the random is called first:
{% set assets = craft.assets.limit(null) %}

{% for homesEntry in craft.entries.section('homes').limit(8).order('RAND()') %}
    {% if homesEntry.homeImages|length %}
        {% set asset = homesEntry.homeImages.first() %}

        {% if asset %}
            
        {% endif %}
    {% endif %}
{% endfor %}

Any help is appreciated.

**Tags:** assets, limit, random


---

## 1 answers

### Answer by username_0 on 2015-07-21. Score: 3

This is how you do it in case anyone is looking for this.
{% set assets = craft.assets.limit(null) %}

{% set randomEntry = craft.entries.section('homes').order('RAND()').relatedTo({
    targetElement: assets,
    field: 'homeImages'
}) %}

{% for homesEntry in randomEntry.limit(6) %}
    {% set asset = homesEntry.homeImages.first() %}

    {% if asset %}
        
    {% endif %}
{% endfor %}


---

