fiddlestacks fiddlestacks - 1 year ago 204
Twig Question

Get two random items from a list in Twig

I have a list of items in Twig, that looks like this.

{% set listItems = [
{ "name":"Bob","title":"Director","text":"Bob like burgers." },
{ "name":"Sue","title":"Manager","text":"Sue loves cash registers." },
{ "name":"Tim","title":"Assistant","text":"Tim doesn't like anything." }
] %}

I would like to get two of the three available people randomly in Twig so that I can display two profiles in a block of my site. (Like a rotating double-feature!)

I cannot find a way using the Twig Docs to do this, but I may be thinking about it wrong.

Answer Source

You can install the array extension and then combine shuffle with @user1453870's answer :

{% for item in listItems|shuffle|slice(0,2) %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download