3

I have quotes inside a global matrix which i want to output randomly on the homepage but without the first quote-block. this does not work:

{% set quotes = city.cityBlocks.offset(1) %}
{% set randomQuotes = quotes.limit(1).order('RAND()') %}

the offset in 'quotes' works fine but the first block is still in randomQuotes anyway.

3
  • All that code would do is output the second block (which is all you'll ever get when offset=1 and limit=1). Have you tried removing the limit parameter? – Brandon Kelly Sep 2 '14 at 5:19
  • thanks brandon, but that will just give me all the quotes. – portnull Sep 2 '14 at 20:28
  • Sorry, I understand what you’re trying to do now. – Brandon Kelly Sep 2 '14 at 20:46
3

That query would basically tell MySQL to do this:

  1. Shuffle the blocks
  2. Return the second one

Since the shuffling happens before the offset/limit params get applied, they can’t be used to exclude the first block, since the first block will already be put in some random position by that point.

Instead you should get the ID of the first block, and exclude it using that:

{% set firstBlockId = city.cityBlocks.limit(1).ids()|first %}

{% if firstBlockId %}
    {% set randomQuotes = city.cityBlocks.id('not '~firstBlockId).order('RAND()') %}
    ...
{% else %}
    There were no blocks...
{% endif %}
2

okay, shuffle seems to work: first set these:

{% set quotes = city.cityBlocks.offset(1) %}
{% set randomQuotes = shuffle(quotes) %}

then slice the the for loop like this

{% for block in randomQuotes|slice(1,1) %}
...
{% endfor %}

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.