3

Assuming that I have a website that uses LESS and utilizes variables; I was wondering if a library or anything exists to provide the end-user the ability to change the variable. For example, if the background color of a class is specified in a variable, I would want to be able to edit it in maybe a dropdown menu. I am going to implement something similar, so prior to doing so, was wondering of any existing solutions.

zallarak
  • 5,287
  • 7
  • 38
  • 54

2 Answers2

3

I've come across this problem often lately and after trying many things my solution is to eventually ditch LESS and go with Stylus, which has a nice JavaScript API.

In any case, this is what I have working right now to get LESS variables in JavaScript:

var getLessVar = function (name, prop) {
  var value = $('<div class="' + name + '"></div>').hide().appendTo('body').css(prop)
  $('.' + name).remove()
  return /^\d+/.test(value) ? +value : value
}

It's hacky but works. You create a class in LESS and assign the variable you want to get in JS to a property, let's say width, but it can be any other property, depending of the type of data you're sending (numbers, colors...)

@myvar: 30px + @foo;
.myvar { width: @myvar }

Then in JS you grab the variable with that lil' script like this:

var myvar = getLessVar('myvar', 'width')

This is not great for performance as it creates an invisible element to retrieve the data but it works.


To set a variable from JS is more complicated, but you can always do some AJAX magic together with LessPHP and some basic parser to read your variables.less.

But again, if you need more power just go with Stylus.

elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • Wow thanks for your solution. Even though I may not use it, it really helped me think about the problem. – zallarak Jul 26 '12 at 01:42
1

modifyVars enables modification of LESS variables in run-time. When called with new values, the LESS file is recompiled without reloading. Simple basic usage:

less.modifyVars({
    '@buttonFace': '#5B83AD',
    '@buttonText': '#D9EEF2'
});
Orwellophile
  • 13,235
  • 3
  • 69
  • 45