LESS combine ruleset into two with different varia

2019-01-27 05:25发布

问题:

I'm trying to combine one ruleset into two different rulesets with variable values swapped. Main purpose is LTR/RTL internationalization.

Usage:

h1 {
  margin-top: 10px;
  .directions({
    margin-@{left}: 5px;
  });
}

Expected output:

h1 {
  margin-top: 10px;
}
.ltr h1 {
  margin-left: 5px;
}
.rtl h1 {
  margin-right: 5px;
}

I was able to get some results with the Passing Rulesets to Mixins function available in Less 1.7

.directions(@rules) {
  @left: left;
  .ltr & { @rules(); }
  @left: right;
  .rtl & { @rules(); }
}

The problem is that the @left variable is always set to the last value used in .directions() mixin (right in this case). Is there any way how to swap variable or pass it back outside of the mixin?

Note: I do not want to output LTR/RTL to two separate files, I'm trying to combine them into one file.

回答1:

To understand Less variables scope and life-time see:

  • Lazy Evaluation (aka Lazy Loading).
  • Variable Semantics
  • Most Misunderstood
  • Scope
  • Last Declaration Wins

The solution for your particular case is as simple as:

.directions(@styles) {
    .ltr & {
        @left: left;
        @styles();
    }
    .rtl & {
        @left: right;
        @styles();
    }
}