Search code examples
lessbem

File-level less variables


I want to define block name at once at head of its file

@block: widget-a;

And then use it in selectors

.@{block} {
    // my styles
}

But I can't do it when I have more than one block. Variable @block takes the last value and it breaks my selectors

// file a.less
@block: widget-a;
.@{block} {
    // styles for widget-a
}

// file b.less
@block: widget-b;
.@{block} {
    // styles for widget-b
}

Both rulesets there got the block .widget-b in spite of that is different files. Is there a way to persist name for each block?

Here is a gist: https://gist.github.com/just-boris/a86f3646f48683a9bf17 which can be built and reproduce it. I use less 2.3.0


Solution

  • I'm not sure why you have to use the same variable name twice? You code does not compile:

    you code:

    // file a.less
    @block: ~".widget-a";
    @{block}: {
        // styles for widget-a
    }
    

    should be:

    // file a.less
    @block: ~".widget-a";
    @{block} {
        // styles for widget-a
    }
    

    can be rewritten to, see variable-interpolation:

    @block: widget-a;
    .@{block} {
        // styles for widget-a
        color: red;
    }
    

    As already mentioned by @harry, when defining the same variable twice in the same scope, the last declaration wins. You could wrap your code in a mixin or use namespaces:

    // file a.less
    .a() {
    @block: widget-a;
    .@{block} {
        // styles for widget-a
        color: red;
    }
    }
    .a();
    
    // file b.less
    .b() {
    @block: widget-b;
    .@{block} {
        // styles for widget-b
        color:blue;
    }
    }
    .b();
    

    outputs:

    .widget-a {
      color: red;
    }
    .widget-b {
      color: blue;
    }