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.

865 thoughts on “Simple FreeMarker random number generator

  1. UpvoteRocket is the #1 automated voting service for private MMORPG servers. Climb toplist rankings on XtremeTop100, TopG, GTop100 with smart undetectable automation. Ragnarok, WoW, Mu Online & 20+ platforms supported. Pay only for delivered votes.

  2. Our AI-optimized solution brings keyword and location-targeted traffic to your website, offering better value than costly paid advertising. Reach out to see results.

    https://marketingaged.com/

  3. Attract high-quality visitors to your site with our AI-driven traffic solution, far more affordable than traditional paid advertising. Ready to boost your conversions?

    https://marketingaged.com/

  4. Save on marketing costs with our AI-powered traffic solution, bringing engaged visitors for less than traditional paid advertising. Start scaling your site now.

    https://marketingaged.com/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>