James Donnelly
James Donnelly

Reputation: 128781

Concatenate a variable and a string to reference another variable in LESS

I have a large list of variables which denote colours. For example, @Yellow-100 is a pale shade of yellow and @Purple-900 is a dark shade of purple.

I have a @Page-Background variable which currently points directly to @Yellow-100, along with several other variables which point to various other shades of yellow.

@Page-Background: @Yellow-100;

...but I'm wanting to set a base colour to use throughout my app so that I can easily switch between different colours without having to rename all of these variables. I've therefore defined the following variable:

@Base: Yellow;

I've read through LESS's Variables documentation, but it doesn't mention how to reference another variable with a variable and a string. @@Base will reference @Yellow, but @@Base-100 doesn't reference @Yellow-100; nor does @@{Base}-100 or @{@Base}-100.

How can I point my @Page-Background variable to my @Yellow-100 variable by replacing Yellow with @Base?

Upvotes: 1

Views: 76

Answers (1)

Harry
Harry

Reputation: 89750

There are two things that need to be addressed here:

  1. When we assign a color name to a variable, Less would by default convert it to the hex value in earlier versions of the compiler, so it is better to use the value within quotes to make Less realize it is a String and not a Color. This issue has now been addressed and so if you are using a newer version of Less compiler, this step might probably not be required.
  2. We have to form the derived variable's name by concatenating the number to the @Base variable's value and then evaluate it.

Putting both together, the below code should work:

@Yellow-100: #fff;

@Page-Background: ~"@{Base}-100"; /* this will form the variable name */
@Base: "Yellow";

a{
    background: @@Page-Background; 
    /*using double @ references the variable whose name is contained in @Page-Background */
}

Upvotes: 1

Related Questions