0

I'm trying to serve a random image picked from an array in Less.

Here's what I have so far:

@images = ['ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg'];
@randomimage: `images[Math.floor(Math.random() * images.length)]`;
 
#footer-widgets .container .row {
    background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}

I think I'm doing some syntax error though. Is that the way to call a variable inside a URL (path/@{randomimage})?

TylerH
  • 20,799
  • 66
  • 75
  • 101
MultiformeIngegno
  • 6,959
  • 15
  • 60
  • 119
  • 2
    Looking at your LESS I see some JS, Is that allowed? also, your LESS will be converted to CSS and CSS is static, the Image is chosen **once** when compiling the LESS. Note: I don't use LESS and barely know about it's syntax. – DividedByZero Oct 30 '14 at 16:42
  • According to this answer it seems possible: http://stackoverflow.com/a/19869095/1342772 – MultiformeIngegno Oct 30 '14 at 16:50

1 Answers1

1

An working example of your code can be found below:

@images: 'ancora.svg', 'timone.svg', 'corda.svg', 'bussola.svg';
@length: length(@images);
@random: `Math.ceil(Math.random() * (@{length}))`;
@randomimage: extract(@images,@random);

#footer-widgets .container .row {
    background: url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0);
}

Notice that "array" in Less can be defined as lists, also see: Loop through array of variable names in Less The first index of Less list is 1

Unless you compile your Less code client side (recompile the code for every request) you should take the comment of @Random-User into account. Indeed the compiled CSS is static and the randomize do not seems the make sense.

Community
  • 1
  • 1
Bass Jobsen
  • 48,736
  • 16
  • 143
  • 224
  • The output is `@randomimage: extract(@images,@random); #footer-widgets .container .row{background:url("//website.com/path/@{randomimage}") no-repeat scroll right 60px bottom 40px rgba(0,0,0,0)}` Seems like `extract` isn't parsed. I'm using LESS pre-processor included in Jetpack by Automattic – MultiformeIngegno Oct 30 '14 at 23:36
  • Probably that pre-processor does not support native javascript calls at all. – Bass Jobsen Oct 30 '14 at 23:45