Simplifying Repetitive LESS

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-28 10:04:46

问题


I am creating a themeing system for a WordPress network that supports multiple layout themes that can support color schemes for a variety of universities. To do so, I periodically compile a LESS file (using lessphp) with school-specific variables and essentially use it as a library of helper classes in the themes.

Each school has 3 colors defined in LESS as: @primary, @secondary and @tertiary. The method is straightforward and functional but requites a lot of repetition in the code. For example:

//Modifier Classes
  .primary-lighter-text {
      color: lighten(@primary,20);
  }
  .sec-lighter-text {
      color: lighten(@secondary,20);
  }
  .tert-lighter-text {
      color: lighten(@tertiary,20);
  }
//Backgrounds
  .primary-bg {
      background-color: @primary;
  }

  .sec-bg {
      background-color: @secondary;
  }

  .tert-bg {
      background-color: @tertiary;  
  }

//Borders
  .primary-border{
      border-color: @primary;
  }
  .sec-border {
      border-color: @secondary;
  }
  .tert-border {
      border-color: @tertiary;      
  }

Nothing complicated from a LESS standpoint, but if I want to add a new helper class, I have to create 3. Is there a more succinct way to achieve this?


回答1:


You can simplify it by making use of array loops. All you have to modify in case of a new addition would be to modify the array variables at the end.

.loop-column(@index) when (@index > 0) { /* Recursive Mixin with Guard condition. Mixin is processed only when the condition is satisfied */
  .loop-column(@index - 1); /* Call the mixin again with a decremented counter */
  @ctype:  extract(@type, @index); /* Extract the type value corresponding to the index from the array */
  @color:  extract(@colors, @index); /* Extract the color value corresponding to the index from the array */

  /* Form and Output the necessary classes and properties */
  .@{ctype}-lighter-text { /* Selector interpolation to dynamically form the selector */
    color: lighten(@color,20);
  }
  .@{ctype}-bg {
    background-color: @color;
  }
  .@{ctype}-border{
    border-color: @color;
  }  
}

.loop-column(length(@type));

@type: primary, sec, tert; /* The color types array */
@colors:#fff, #777, #000; /* The color value array for each type */
/* If required the colors can be kept as separate variables also. Refer 2nd demo. */

Demo | Demo 2

Update: (Based on comments from Andrew Cafourek and seven-phases-max)

Since LessPHP is outdated, the following line should be added and the length(@type) should be replaced with the actual count.

.loop-column(0) {};
.loop-column(4);


来源:https://stackoverflow.com/questions/24757612/simplifying-repetitive-less

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!