Skip to content

Instantly share code, notes, and snippets.

@samsolomon
Last active September 30, 2019 02:52
Show Gist options
  • Save samsolomon/27cf76b8ab64c56346c5 to your computer and use it in GitHub Desktop.
Save samsolomon/27cf76b8ab64c56346c5 to your computer and use it in GitHub Desktop.
This code will work to give you a random number to use in Liquid. Works in customer.io.
<!--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 }}
@konung
Copy link

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