SASS:从类列表中生成变量列表(反之亦然)

时间:2014-01-20 12:34:47

标签: css variables sass

我有附加值的变量列表以及与变量同名的相应类列表,如下所示:

$cold-world: Verdana, sans-serif;
$cream: Verdana, sans-serif;
$fish: Verdana, sans-serif;
$knowledge-god: Verdana, sans-serif;
$run: test, test, Verdana, sans-serif;
$winter-warz: Verdana, sans-serif;

$font-list: $cold-world, $cream, $fish, $knowledge-god, $run, $winter-warz;

$pages: "cold-world", "cream", "fish", "knowledge-god", "run", "winter-warz";

由于两个列表都是相同的,我试图保留DRY并创建函数,为$pages列表中的每个类添加前缀$符号。然后我使用@each循环来创建$font-list

$font-list: (); // initilaze empty list

@function variable($x) {
    @return unquote("$" + $x);
}

@each $page in $pages {
    $font-list: append($font-list, variable($page), comma);
}

问题是当我尝试在输出循环中使用生成列表时。我得到变量名而不是值

@mixin font($font-stack, $stack: 1) {
    font-family: nth($font-stack, $stack);
}

@each $page in $pages {
    .#{$page} {
        @include font(nth($font-list, index($pages, $page)), 1);
        //@include font(variable($page), 1); // same result as above
    }
}

DEMO

我也尝试使用str-slice选项(在SASS 3.3.0中提供)从类列表中生成变量列表也没有avil。它输出变量值代替类名。

$font-list: $cold-world, $cream, $fish, $knowledge-god, $run, $winter-warz;

$pages: ();

@function slice($x) {
  @return str-slice(#{$x},1,100);
}

@each $variable in $font-list {
  $pages: append($pages, slice($variable), comma);
}

DEMO#2

1 个答案:

答案 0 :(得分:1)

我设法使用nested lists获得了我想要的结果。通过在@each循环代码中创建其他变量,代码变得非常简洁(并且在libsass和当前sass中都有效)。

$pages:
"cold-world" font1 sans-serif,
"cream" font2 sans-serif,
"fish" font3 sans-serif,
"knowledge-god" font4 sans-serif,
"run" font5 sans-serif,
"winter-warz" font6 sans-serif;


@mixin font($font-stack, $stack: 1) {
    font-family: nth($font-stack, $stack);
}

@each $page in $pages {

    $class: nth($page, 1);
    $font-stack: ();

  @for $i from 2 through length($page) {
    $font-stack: append($font-stack, nth($page, $i));
  }

    .#{$class} {
        @include font($font-stack, 1);
    }
}

DEMO