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.

460 thoughts on “Simple FreeMarker random number generator

  1. Our AI-powered solution drives location-specific visitors to your site, delivering better results than paid ads at a lower cost. Reach out to learn more.

    https://ow.ly/nNVw50XSIIZ

  2. Attract high-intent, keyword and location-targeted traffic to your site with our AI-optimized solution, far more affordable than traditional paid ads. Start scaling now.

    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://marketingager.com/

  4. Boost your website’s audience with our AI-powered traffic service, delivering targeted visitors at a lower cost than paid ads. Contact us today.

    https://cutt.ly/EtQitYXz

  5. Attract high-intent, keyword and location-targeted traffic with our AI-driven service, far more affordable than paid advertising. Connect with us today.

    https://ow.ly/KJL650XSItJ

  6. Save big with our AI-powered traffic service, sending keyword-targeted visitors from specific locations to your website for less than paid ad campaigns. Learn more today.

    https://cutt.ly/EtQitYXz

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>