2012-01-23 49 views
2

我已經開始在一個小型Web項目中使用JSON數據結構而不是XML。我需要對數據進行一些轉換,就像您通常在XML上使用XSLT時所做的那樣,然後我就st upon在很酷的庫http://tempojs.com上。使用Tempo轉換樹結構

但是,當我意識到,我的數據是一個樹結構,並且我想在轉換中需要一些遞歸時,出現了真正的問題。

這裏的數據結構的一個樣本:

[ 
     { 
      "text" : "The sun is shining", 
      "children" : [] 
     }, 
     { 
      "text" : "it's cloudy.", 
      "children" : 
      [ 
       { 
        "text" : "It's raining.", 
        "children" : [] 
       }, 
       { 
        "text" : "The sun was shining.", 
        "children" : [] 
       }, 
       { 
        "text" : "A rainbow appeared.", 
        "children" : 
        [ 
         { 
          "text" : "A pot of gold was found at the end of the rainbow.", 
          "children" : [] 
         }, 
         { 
          "text" : "The gold returned more than a million dollars, when sold.", 
          "children" : [] 
         } 
        ] 
       } 
      ] 
     } 
    ] 

而且我想變成一個嵌套的HTML列表如下:

<ul> 
    <li>The sun is shining</li> 
    <li>it's cloudy. 
     <ul> 
      <li>It's raining.</li> 
      <li>The sun was shining.</li> 
      <li>A rainbow appeared. 
       <ul> 
        <li>A pot of gold was found at the end of the rainbow.</li> 
        <li>The gold returned more than a million dollars, when sold.</li> 
       </ul> 
      </li> 
     </ul> 
    </li> 
</ul> 

任何想法如何可以利用速度來完成?

回答

-1

我不知道節奏,我使用underscore.js代替。

這將是這樣的:

var mytemplate = " 
<%= text %> 
<ul> 
    <% _.each(children, function(child){ %> 
    <li><%= child.text %></li> 
    <li><%= _.template(mytemplate, child.children) %> 
    </li> 
</ul> 
"; 

var htmlResult = _.template(mytemplate, myJSON); 
0

天寶1.x中不能處理的模板嵌套多個級別。然而,2.0-dev分支支持這一點,在我看來正確地呈現您的數據:http://jsfiddle.net/mr_olafsson/wLEQs/

請注意,該示例確實意味着固定(和相等)數量的級別/嵌套模板。讓我知道你是怎麼辦的!這麼晚纔回復很抱歉。