Wex
Wex

Reputation: 15715

Change variable used in mixin depending on scope

In the Lazy Loading section of the Less language features, it states:

When defining a variable twice, the last definition of the variable is used, searching from the current scope upwards. This is similar to css itself where the last property inside a definition is used to determine the value.

I'd like to overwrite a global variable, but this doesn't seem to work:

@border: #fff;

.table {
  border: @border;
}

.table-summary {
  @border: #000;
  .table
}

Compiles to

.table {
  border: #ffffff;
}
.table-summary {
  border: #ffffff; // I want this to be #000
}

Upvotes: 0

Views: 174

Answers (1)

seven-phases-max
seven-phases-max

Reputation: 11820

Currently the global scope has higher precedence than caller scope for a mixin (unless the mixin is defined inside parametric namespace). For more more details see #1316, some people consider this is a bug but there's no well-defined agreement on that.

Either way, the recommendation is to minimize use of non-parametric mixins and to not rely on indirect parameter passing whenever possible. Your example is a perfect use-case for a parametric mixin (even if your the code becomes slightly more verbose):

@border-default: #fff;

.table-base(@border: @border-default) {
    border: @border;
}

.table {
    .table-base;
}

.table-summary {
    .table-base(#000); 
}

Alt. if for some reason you can't modify the .table class (for example if it's defined in an external library) then just forget about any variables and override the property directly, the most optimal way would be:

@border: #fff;

.table {
    border: @border;
}

.table-summary:extend(.table) {
    border-color: #000;
}

---

Technically, there's method to achieve what you want with the code quite close to your original snippet but I doubt it is something to be really recommended:

@border: #fff;

.table {
    border: @border;
}

.-;.-() { // dummy parametric namespace

.table-summary {
    @border: #000;
    .table;
}

} // end of dummy parametric namespace

Upvotes: 1

Related Questions