Skip to content

Less Language String Interpolation

Mária Jurčovičová edited this page Feb 26, 2015 · 4 revisions

Use @{variable} syntax inside string to use variable value. If variable variable exists, the expression is replaced by variable value. If parentheses does not contain valid variable name, the expression is left as it is.

Sample input:

@variable: 32;
#stringInterpolation {
  text: "@{variable} @{not a variable name}";
}

Compiled css:

#stringInterpolation {
  text: "32 @{not a variable name}";
}

Note: less4j and less.js behave differently if parentheses contains valid variable name, but such variable does not exist. Less4j leaves the expression as it is and less.js throws an exception.

Nested Interpolation

If referenced variable contains another string, that string is interpolated just before being used:

@final: "outer scope";
@interpolated: "@{final}";
@reference: "@{interpolated}";
#workingChain {
  @final: "inner scope";
  text: "@{reference}";
}

Compiled css:

#workingChain {
  text: "inner scope";
}

Only referenced variable value is interpolated, not the whole interpolated string:

#faultyChain {
  @bbb: "ccc";
  @aaa: "bbb";
  text: "@{@{aaa}}"; // will print text: "@{bbb}";
}

#anotherTrick {
  @bbb: "ccc";
  @aaa: "@{";
  text: "@{aaa}bbb}"; // will print text: "@{bbb}";
}

Compiled result:

#faultyChain {
  text: "@{bbb}";
}
#anotherTrick {
  text: "@{bbb}";
}

Named and Shorthand Colors

Shorthand colors are converted into their hex codes before being printed. Named colors keep their original form.

#nonString {
  @namedColor: green; 
  named: "@{namedColor}";
  @shorthandColor: #123; 
  shorthand: "@{shorthandColor}";
}

Compiled result:

#nonString {
  named: "green";
  shorthand: "#112233";
}