简化重复性

时间:2014-07-15 11:55:41

标签: less lessphp

我正在为WordPress网络创建一个主题系统,该系统支持多种布局主题,可以支持各种大学的配色方案。为此,我定期使用学校特定的变量编译LESS文件(使用lessphp),并基本上将其用作主题中的辅助类库。

每所学校在LESS中定义了3种颜色:@primary@secondary@tertiary。该方法简单实用,但需要在代码中重复大量重复。例如:

//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;      
  }

从LESS的角度来看,没有什么比这更复杂了,但是如果我想添加一个新的帮助类,我必须创建3.有没有更简洁的方法来实现这个目标?

1 个答案:

答案 0 :(得分:3)

您可以通过使用数组循环来简化它。在新添加的情况下,您只需要修改数组变量即可。

.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

更新(基于Andrew Cafourekseven-phases-max的评论)

由于LessPHP已过时,因此应添加以下行,并将length(@type)替换为实际计数。

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