Simple FreeMarker random number generator

FreeMarker doesn’t have a random number generator function. I needed a really simple solution that would allow me to pick a random image URL to be displayed on the homepage.

<#--
* Generates a "random" integer between min and max (inclusive)
*
* Note the values this function returns are based on the current
* second the function is called and thus are highly deterministic
* and SHOULD NOT be used for anything other than inconsequential
* purposes, such as picking a random image to display.
-->
<#function rand min max>
  <#local now = .now?long?c />
  <#local randomNum = _rand +
    ("0." + now?substring(now?length-1) + now?substring(now?length-2))?number />
  <#if (randomNum > 1)>
    <#assign _rand = randomNum % 1 />
  <#else>
    <#assign _rand = randomNum />
  </#if>
  <#return (min + ((max - min) * _rand))?round />
</#function>
<#assign _rand = 0.36 />

I’ve added this function to the FreeMarker Spring extensions I’ve been building up. You might use it in your code like so:

<img src="<@spring.url "/images/" + springx.rand(1, 10) + ".jpg" />" />

Note that there are obvious issues with this function. Aside from being based heavily on the second the function is called, you’ll notice that the min and max have less probability of being generated as the other values…what? I said it was simple.