Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This code will work to give you a random number to use in Liquid. Works in
<!--create a semi-random number using the last second of the send date-->
{% capture time_seed %}
{{ 'now' | date: "%s" }}
{% endcapture %}
<!--manupulate using lots of maths-->
{% assign random = time_seed | times: 1103515245 | plus: 12345 | divided_by: 65536 | modulo: 32768 | modulo: 10 %}
<!--return number-->
{{ random }}

This comment has been minimized.

Copy link

@konung konung commented Aug 21, 2019

Hi. Thank you for sharing this.

I'm also looking for a solution to getting a random number, but I don't think it's possible in Liquid, to get a random number (for most intents and purposes) for EACH request.

My approach is similar to yours. But there is a problem.

The problem is with how Liquid is used - generally speaking it's used either in static or highly cached pages. That means the time_seed doesn't change until the page is regenerated by the server.

{{ 'now' | date: "%s" }} is not the "current time", it is the "current time at the moment of generating this page, which will be cached until next update"

This can be fine for some uses, but not if you need a random number for EACH request.

As far as I can tell there is no way to surcumvent this in pure Liquid.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.