LoginSignup
1
1

More than 5 years have passed since last update.

Stylusで文字列連結して変数を生成する

Last updated at Posted at 2016-07-26

「Stylusで、変数をloopで回して動的に変数を生成する」

イメージとしては

stylus
// $color_1 = red
color '$color_' + 1  // color: red; と出力したい

こういう感じの変数展開がしたい。
しかし上記のコードだと

css
color: '$color_1';

と展開されてしまうのでだめ。
ということに去年だったか悩んでたんですが、普通に関数が用意されてました…ということでメモ。

DEMO: https://codepen.io/tokimari7/pen/oLyjbv

Stylusのlookup() というbuilt in functionを使えばできます。

lookup(name)
Allows to lookup a variable with a given name, passed as a string. Returns null if the variable is undefined.
Useful when you need to get a value of a variable with dynamically generated name:

jade
ul
  each i in [1,2,3]
    li(class="item--#{i}").item color
stylus
$color_1 = red
$color_2 = blue
$color_3 = green
.item
  for $idx in (1..3)
    &--{$idx}
      color lookup('$color_' + $idx)

output image:
image

おまけ

zeroPaddingも base-convert() で代用できる。

stylus
$color_01 = red
$color_02 = blue
$color_03 = green
.item
  for $idx in (1..3)
    $key = base-convert($idx, 10, 2)  // 10進数、2桁のzeroPadding
    &--{$key}
      color: lookup('$color_' + $key)

連番のスタイル生成に便利。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1