2012-05-12 67 views
1

隨着dust.js,是它能夠輸出JSON關鍵?Dust.js輸出JSON關鍵

即我如何輸出的關鍵「名」和「個人資料」沒有硬編碼他們在我的模板?

{ 
name: "Foo", 
profile: { 
      name: "Bar" 
     } 
} 

最終文本,JSON密鑰名稱和配置文件沒有條碼。

name Foo 
profile - name - Bar 

回答

-1

灰塵沒有內置因爲哲學,JSON不應該有一個關鍵數據此功能。考慮將您的數據模型更改爲類似:

{ 
    name: "Foo", 
    profile: { 
    fields: [ 
     { 
     title: "name", 
     value: "Bar" 
     } 
    ] 
    } 
} 
3

確定您可以。定義一個部分,像這樣:

{@keyvalue:cont} 
    {key} - {value} 
{/keyvalue} 

然後重新定義像這樣JSON上下文:

cont:{ 
    name: "Foo", 
    profile: "Bar" //I'm simplifying this a bit for the sake of this example 
} 

這是使得用於鍵值部上下文上述被約束到只有「續」。那麼你可以這樣定義鍵值助手:

"keyvalue": function(chunk, context, bodies){ 
    var items = context.current(), //this gets the current context hash from the Context object (which has a bunch of other attributes defined in it) 
     ctx; 

    for (key in items) { 
    ctx = {"key" : key, "value" : items[key]}; 
    chunk = chunk.render(bodies.block, context.push(ctx)); 
    } 

    return chunk 
} 

應該做的伎倆。在dustjs網站上對此進行了測試。希望你可以加入到這個嵌套哈希。

例如,如果你需要定義在上下文HTML標籤的屬性,這是特別有用的 - 我不希望有獨立的鍵定義一組屬性,然後相應的設定值。我希望他們在一起。更易於閱讀,更易於管理。

2

下面的方法幾乎一樣@ asyraf9的答案,但沒有重新定義JSON和使用示例。

dust.helpers.iterate = function(chunk, context, bodies, params) { 
    params = params || {}; 
    var obj = params['on'] || context.current(); 
    for (var k in obj) { 
     chunk = chunk.render(bodies.block, context.push({key: k, value: obj[k]})); 
    } 
    return chunk; 
} 

來源:https://github.com/rashad612/dustjs-helpers/commit/9039130dc060a4bf3e93856601891a7da9047bac

使用它在模板等:

{#myobject.myarray} 
    {@iterate on=.} 
     {key} - {value} 
    {/iterate} 
{/myobject.myarray} 

它顯示的陣列內的所有對象的鍵和值。