Reputation: 3183
I cannot get LESS to correctly parse a variable and then pass it to javascript.
@bp1 : "lorem";
@bp2 : "ipsum";
@bp3 : "foo";
@bp4 : "bar";
@bp5 : "baz";
@bp6 : "ham";
@bpN: 6;
.loopingClass (@index) when (@index > 0) {
@val: ~'@{bp@{index}}';
@value: ~'"@{val}".toUpperCase()';
@media screen and (min-width: @value) {
body { font-family: ~'"@{bp@{index}}"'; }
}
.loopingClass(@index - 1);
}
.loopingClass (0) {}
.loopingClass (@bpN);
The follow code results in:
@media screen and (min-width: "ham".toUpperCase()) {
body {
font-family: "ham";
}
}
@media screen and (min-width: "baz".toUpperCase()) {
body {
font-family: "baz";
}
}
@media screen and (min-width: "bar".toUpperCase()) {
body {
font-family: "bar";
}
}
@media screen and (min-width: "foo".toUpperCase()) {
body {
font-family: "foo";
}
}
@media screen and (min-width: "ipsum".toUpperCase()) {
body {
font-family: "ipsum";
}
}
@media screen and (min-width: "lorem".toUpperCase()) {
body {
font-family: "lorem";
}
}
I'm trying to dynamically set the variable, and then interact with it with javascript. What am I missing here? Is this even possible with LESS?
Upvotes: 0
Views: 129
Reputation: 11820
The correct syntax for inline javascript evaluation is using backticks. So with other minor fixes your code becomes:
@bp1 : "lorem";
@bp2 : "ipsum";
@bp3 : "foo";
@bp4 : "bar";
@bp5 : "baz";
@bp6 : "ham";
@bpN: 6;
.loopingClass (@index) when (@index > 0) {
@val_: 'bp@{index}';
@val: @@val_;
@value: ~`@{val}.toUpperCase()`;
@media screen and (min-width: @value) {
body { font-family: @val; }
}
.loopingClass(@index - 1);
}
.loopingClass (0) {}
.loopingClass (@bpN);
And with quoting overuse removal and further optimizations (LESS 1.4.0 and higher):
@bp: "lorem",
"ipsum",
"foo",
"bar",
"baz",
"ham";
@bpN: 6;
.loopingClass(@bpN);
.loopingClass(@index) when (@index > 0) {
.loopingClass(@index - 1);
@lowercase: extract(@bp, @index);
@uppercase: ~`@{lowercase}.toUpperCase()`;
@media screen and (min-width: @uppercase) {
body {font-family: @lowercase}
}
}
Upvotes: 3