【问题标题】:Stylus: Is there a Way to make this DRYer手写笔:有没有办法制作这个 DRYer
【发布时间】:2018-08-01 06:13:30
【问题描述】:

我有许多我希望循环遍历的哈希值。

例如,我有一个颜色哈希:

colors = {
  red: #f00f00,
  green: #78f000,
  blue: #0090f0,
}

还有一个sizes哈希:

fontSize = {
  small:  14px,
  base:   16px,
  large:  18px
}

然后我遍历这些哈希。这是一个简化的例子:

for name, color in colors
  .{name}
    background-color: color

for name, size in fontSize
  .{name}
    font-family: size

我想知道是否有烘干机可以做到这一点。即,我不想一遍又一遍地重写 for...in 循环(因为每个哈希的结构相同。

有没有办法做到这一点(如果有,怎么做)?

【问题讨论】:

    标签: dry stylus


    【解决方案1】:

    您可以使用循环执行函数并使用参数来获取类名并设置您需要的属性:

    手写笔

    colors = {
      red: #f00f00,
      green: #78f000,
      blue: #0090f0
    }
    
    fontSize = {
      small:  14px,
      base:   16px,
      large:  18px
    }
    
    loop(hashname, prop)
      for class, value in hashname
        .{class}
          {prop}: value
    
    
    loop(colors, background-color)
    
    loop(fontSize, font-size)
    

    输出

    .red {
      background-color: #f00f00;
    }
    .green {
      background-color: #78f000;
    }
    .blue {
      background-color: #0090f0;
    }
    .small {
      font-size: 14px;
    }
    .base {
      font-size: 16px;
    }
    .large {
      font-size: 18px;
    }
    

    【讨论】:

    • 谢谢 - 我会试试看。
    • 我发现了另一个潜在的解决方案——但它有一个不同的问题需要解决。如果可以的话,你介意看看吗:stackoverflow.com/questions/48927820/…
    • 我正在尝试为您的其他问题找到解决方案,我不确定是否可以这样做
    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多