2015-07-11 51 views
1

下面的代碼不會生成HTML。下劃線不會生成HTML

下劃線模板:

<script type="text/template" id="features-template"> 
     <li class="list-group-item"> 
     <span class="badge"><%= score %></span> 
     <%= prediction %> 
     </li> 
</script> 

JSON:

{ 
    "features": { 
     "status": true, 
     "response": { 
      "predictions": [ 
       ["shirt", "90.12"], 
       ["jeans", "09.88"] 
      ] 
     } 
    } 
} 

jQuery代碼:

var predictions = []; 

_.each(response.features.response.predictions, function(prediction, i) { 
    predictions.push({ 
      prediction: prediction[0], 
      score: prediction[1] 
    }); 
}); 

var tpl = _.template(featureTemplate, predictions)); 

console.log(tpl); 

我可以看到的預測陣列與值創建。

爲什麼這段代碼不能生成正確的HTML?

回答

1

我使用最新版本的下劃線(1.8.3)進行了測試,其他版本可能有差異。

documentation of _.template說,數據後給予的模板編譯:

var compiled = _.template(featureTemplate); 
var tpl = compiled({predictions:predictions}); 

我還添加在模板中的foreach循環:

<script type="text/template" id="features-template"> 
    <% _.each(predictions, function(prediction) { %> 
    <li class="list-group-item"> 
     <span class="badge"><%= prediction.score %></span> 
     <%= prediction.prediction %> 
    </li> 
    <% }); %> 
</script> 
+0

大衛,非常感謝你!它的工作! – San