witrin
witrin

Reputation: 3763

Inheritance with variables overriding

I have defined a class .class which uses a variable @var:

@var: 'value';

.class {
    property: @var;
    // and much more stuff [...]
}

And now I want to inherit from .class and change the value of @var in the same time like this:

.another-class {
    @var: 'another-value';
    .class;
}

But it seems the new value another-value is not taken. How can I achieve this without changing .class?

Upvotes: 0

Views: 309

Answers (2)

seven-phases-max
seven-phases-max

Reputation: 11820

What I'd suggest in a simplest case is just a parametric mixin, e.g.:

@var: value;

.mixin(@parameter: @var) {
    property: @parameter;
}

.class {
    .mixin();
}

.another-class {
    .mixin(another-value);
}

(Unless you need to override too many variables so that the mixin becomes too verbose... But in this case the idea of re-using the styles turns to be flawed itself. A better solution to choose may be too dependable on the real code (what exactly the .class is about and what actually it's doing in context of CSS).

There's looooong discussion about similar use-cases in general at #2435, there're detailed explanation of why actually Less works this way (global scope > caller scope) and other insights of various pros and cons of parameterizing of a mixin via variable overriding instead of explicit parameter passing and/or explicit CSS property overriding).

Upvotes: 1

witrin
witrin

Reputation: 3763

Ok this question seems to be a duplicate of "Can I override global variables from the calling scope". And I found an answer in its comments (https://gist.github.com/seven-phases-max/9473260) but this changes the original class a little bit:

@var: 'value';

.lib() {
    .class() {
        property: @var;
        // and the rest of `.class`
    }
}

.class {
    .lib.class();
}

.another-class {
    @var: 'another-value';
    .lib.class();
}

Upvotes: 0

Related Questions