0

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?

1 Answer 1

3

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}
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

That works, but the @uppercase variable is being wrapped in quotes. Is there a way to avoid that, or do I need to save the output to another variable and then .replace('"','')?
Ah, to remove quotes you can use escaping with backticks too.. (Hmm, I guess I did miss that this was your intention in original example). I've updated my answer with that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.