2016-07-26 82 views
1

我有符合我的觸針和通過在一些數據的構建腳本。迭代中的Stylus嵌套對象

stylus(stylFile) 
    .set('filename', 'index.css') 
    .define('data', require('./data.json')) 
    .render(...) 

的data.json文件包含基團的一個對象,並且每個組是由多個對象中的代表項目。

{ 
    "group1": { 
    "item1": { 
     "width": 1 
    }, 
    "item2": { 
     "width": 2 
    } 
    }, 
    "group2": { 
    "item3": { 
     "width": 3 
    } 
    } 
} 

在我的手寫文件,我想通過組迭代,然後通過自己的物品,像這樣

for group, items in data 
    #{group} 
    for id, item in items 
     #{id} 
     width item.width 

我希望這個輸出是

#group1 #item1 { 
    width: 1; 
} 
#group1 #item2 { 
    width: 2; 
} 
#group2 #item3 { 
    width: 3; 
} 

相反我得到

ParseError: index.css:118:1 
    114| #{group} 
    115|  for id, item in items 
    116|  #{id} 
    117|   width item.width 
    118| 
--------^ 

expected "indent", got "outdent" 
+0

我有一種感覺,這已經是與筆建在我的數據必須得到‘哈希’強迫進入。 – arkanciscan

回答

1

我不知道你是怎麼在觸筆但哈希對象你可以做到這一點得到json

STYLUS

data={ 
    "group1": { 
    "item1": { 
     "width": 1 
    }, 
    "item2": { 
     "width": 2 
    } 
    }, 
    "group2": { 
    "item3": { 
     "width": 3 
    } 
    } 
} 

for group in data 
    #{group} 
    items = data[group] 
    for item in items 
     #{item} 
     for property, value in items[item] 
      {property} value 

輸出

#group1 #item1 { 
    width: 1; 
} 
#group1 #item2 { 
    width: 2; 
} 
#group2 #item3 { 
    width: 3; 
} 

UPDATE

您可以從手寫筆文件得到json哈希對象轉換:

data = json('data.json', { hash: true }) 

for group in data 
    #{group} 
    items = data[group] 
    for item in items 
     #{item} 
     for property, value in items[item] 
      {property} value 
+0

我在構建腳本中使用'define()'函數將json放入手寫筆中。所以NPM打開JSON,將它變成一個JS對象,然後把它交給Stylus,我認爲它將它強制轉換爲散列。 – arkanciscan

+0

很抱歉,使用JSON數據時,您的解決方案對我無效。我得到了#id#{ (null):0;每個項目重複' }。 – arkanciscan

+0

我編輯我的答案,或許對你有用 – blonfu