How do I use a variable in less js as a command that appears before a parenthesis?

I’ve asked this question on Stack Overflow and on Github Issues but I couldn’t get any answers, so maybe this forum can help.

How do I use a variable in less js as a command that appears before a ( bracket or parenthesis?

.breadcrumb li:nth-child(2) a       { background:  darken(@breadcrumbrootback, 5%); }
.breadcrumb li:nth-child(2) a:after { border-left-color:  darken(@breadcrumbrootback, 5%); }

I would like to change darken( to @breadcrumbcolouraction( so the command is chosen based on a variable (so it could be either lighten or darken based on the value or a variable). How do I do this?

@breadcrumbcolouraction: "darken";
@breadcrumbcolouraction: "lighten";

In less version 4.1.1 if I changed darken to the variable @breadcrumbcolouraction, the less file would fail to compile.

I would say no. You can’t use variables to substitute a function name when calling the function. However, you can define a variable to hold the function itself and then use the appropriate variable based on the value of some other variable. You can also define your darken/lighten functions in something like a detached ruleset and then apply the ruleset on some other variable value (which would be useful if you want to use a whole set of rules at once).

@redcolor: #FF0000;
@some-option: "darken";

@dark-set: { background: darken(@redcolor, 5%); }

.box {
  width: 100px;
  height: 100px;
}


 // Color box with dark red detached set @dark-set if option is darken
.box when (@some-option = "darken") {
  @dark-set();
}

While the code above may seem not as direct as you are looking for, you can see how through the use of variables, variables that hold a value that is used as an option, guard clauses and detached sets you can apply variable properties based on the value of a variable elsewhere. If we changed @some-option to something like “lighten” we could define another guard clause definition for .box that could apply a whole other set of definitions.

Perhaps you can see a way to use all these different mechanisms to achieve a workable solution.

2 Likes

I can’t find the when command in the less js documentation, as in the feature being defined and explaining what it. Where can I find it?

Thank your for your help!

That is because that link is pointing to the functions section. It is a guard clause I am talking about, not a function…

:slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.