zotonic

How do you choose a media item at random from a Page Connection in a Zotonic template?


I would like to render a random connected media item in Zotonic as follows:

{% with m.rsc[id].banner as media %} 
    {% if media %}
    {% with media.random as m %}
            {% media m %}
        {% endwith %}
{% endif %} 
{% endwith %}

How do you choose a media item at random from a Page Connection in a Zotonic template?


Solution

  • Not all filters take all kinds of semi-lists. (ie. data structures that can act like a list but aren't, search results and resource lists are examples.)

    You can force a value to be a list and then apply the random filter:

    {% media m.rsc[id].banner|make_list|random %}
    

    Also makes use of the fact that {% media %} on an undefined value returns the empty list.