neoscms

Select a random node on every reload


I want to select a random node on every reload. My fusion file looks like this:

randomInt = ${Math.randomInt(0, q(node).children(Neos.Neos:Document).count()}
randomNode = ${q(node).children(Neos.Neos:Document).get(this.randomInt)}

Unfortunately the result is stored in the cache. That means that only after the cache get flushed a new node will be returned. How can I prevent this? I have already experimented with the cache rules a little bit, but I didn't come up with a solution yet.


Solution

  • The element that I want to use is on every page. That's why something like the unchached mode would be a really bad idea.

    In my situation the output is only a array of strings. So I did following in my Fusion.

    1. Generate "almost" a Array in Fusion

      allMyStrings = Neos.Fusion:Loop {
          items = ${q(node).children(Neos.Neos:Document).get()}
          itemName = 'node'
          itemRenderer = ${"'" + q(node).property('testString') + "'"}
          @glue = ','
      }
      
    2. Pick a random array in JS

      <p id='replaceMe'></p>
      <script>
        var quoteArray = [{allMyStrings -> f:format.raw()}]
        var randomIndex = Math.floor(Math.random() * quoteArray.length);
        var randomElement = quoteArray[randomIndex];
        document.getElementById('replaceMe').outerHTML= '<p>' + randomElement + '</p>';
      </script>
      

    A bit hacky but it works and it don't harm the performance of the website