2013-04-18 73 views
10

看看這個例子:SASS/SCSS對象鍵值環

@include font-face('Entypo', font-files('entypo.woff')); 

.icon { 
    display: inline; 
    font: 400 40px/40px Entypo; 
} 

.icon-star { 
    @extend .icon; 

    &:after { 
    content: "\2605"; 
    } 
} 

.icon-lightning { 
    @extend .icon; 

    &:after { 
    content: "\26A1"; 
    } 
} 

我希望讓事情儘可能的乾燥,所以我想知道如果下面是可能的,如果是的話怎麼辦?

@include font-face('Entypo', font-files('entypo.woff')); 

.icon { 
    display: inline; 
    font: 400 40px/40px Entypo; 
} 

$icons { 
    $star: "\2605"; 
    $lightning: "\26A1"; 
} 

@each $icon in $icons { 
    $key = $icon{key}; // ??? 
    $value = $icon{value}; // ??? 

    .icon-#{$key} { 
    @extend .icon; 

    &:after { 
     content: $value; 
    } 
    } 
} 

回答

23

Sass目前不支持映射。你必須用列表的列表來住了。

$icons: star "\2605", lightning "\26A1"; 

@each $icon in $icons { 
    $key: nth($icon, 1); 
    $value: nth($icon, 2); 

    .icon-#{$key} { 
    @extend .icon; 

    &:after { 
     content: $value; 
    } 
    } 
} 
+0

我討厭SASS的文件,無論如何,非常感謝。 – onlineracoon

+1

如果你想在http://learnboost.github.io/stylus/ –

+0

完美的例子 – lorless

53

薩斯3.3(發佈於2014年3月7日),現在允許你使用地圖:爲什麼我無法找到一個簡單的循環這樣

@include font-face('Entypo', font-files('entypo.woff')); 

.icon { 
    display: inline; 
    font: 400 40px/40px Entypo; 
} 

$icons: (
    star: "\2605", 
    lightning: "\26A1" 
); 

@each $key, $value in $icons { 
    .icon-#{$key} { 
    @extend .icon; 

    &:after { 
     content: $value; 
    } 
    } 
} 
+0

最好的答案,這應該是公認的答案現在。我們有一個很好的方式來更新或審查接受的答案,因爲接受一個已經過時? – nXqd

+0

您可以更新答案突出顯示,運仍然可以改變公認的答案,如果他想。 – zessx

+0

這應該是最好的答案! – Tony