Browser side Javascript evaluation in less file
Hi,
Is it possible to evaluate javascript within less files. For example I would like to assign current screen width to a particular variable. Is it possible to do so using less? I saw javascript test file where javascript expressions are enclosed with `. I tried the same in less files but it didn't fly. So just wanted to check if this feature is available in the current release?
Regards Bhavin
it should work.
@var: `window.location.href`;
should work fine. can you show an example of what you're trying?
@cloudhead will script inside a string work?
@var: "`window.location.href`";
?
It works... However, when I am trying to do any calculation on evaluated value, it does not work. For example,
@height: e(`window.screen.height + "px"`);
padding-bottom: @height
margin-bottom: 0 - @height;
yields
padding-bottom: 800px;
@height: 32767px;
padding-bottom: @height
margin-bottom: 0 - @height;
yields
padding-bottom: 32767px
margin-bottom: -32767px;
The problem caused by the fact that any javascript variable become tree.Anonymous class instance under the hood. This class doesn't provide implementation of 'operate' method, so any operations are impossible. To fix it please, apply following code: less-1.1.3.js lines 1833-1839 Before:
if (typeof(result) === 'string') {
return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
} else if (Array.isArray(result)) {
return new(tree.Anonymous)(result.join(', '));
} else {
return new(tree.Anonymous)(result);
}
After:
if (typeof(result) === 'string') {
var match;
if (match = /^(-?\d*\.?\d+)(px|%|em|pc|ex|in|deg|s|ms|pt|cm|mm|rad|grad|turn)?/.exec(result)) {
return new (tree.Dimension)(match[1], match[2]);
} else if (match = /^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})/.exec(result)) {
return new(tree.Color)(match[1]);
}
return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
} else if (Array.isArray(result)) {
return new(tree.Anonymous)(result.join(', '));
} else {
return new(tree.Anonymous)(result);
}
Now we're checking whether passed js string matches color or dimension declaration and instantiate corresponding instance. It works quite well for me.
Duplicate of #384