2013-06-18 41 views
0

我有一個JSON文件,其中有這樣的JSON數據從Json的獲取HTML數據:無法使用jQuery與Handlebars.js模板

{ 
    "username":"lgangula", 
    "message":"" 
} 
在data.json文件

我得到的文件,使用jquery ajax方法並使用Handlebars.js添加數據;這裏是功能:

var JsonHandler = function(url) { 
     return $.getJSON(url) 
}; 

(function ($) { 

    var manupulate = function(data){ 
     $.each(data, function(key,value){ 
      if(key === "username"){ 
          console.log(value) // i am getting the name 
       var x = Handlebars.compile($("#header-template").html()); 
       console.log(x(value));//i am getting the elements, without the value..!? 
      } 
     }) 
    } 


    var path = "js/data.json"; 
    new JsonHandler(path).done(function(data){ 
     manupulate(data); 
    }) 

})(jQuery); 

我沒有得到我的HTML輸出的價值。這裏是我使用的模板:

<script id="header-template" type="text/x-handlebars-template"> 
     <div class="loginInfo"> <a href="#">{{username}}</a> | <a href="#">Logout</a> </div> 
    </script> 

這裏出什麼問題..任何人都可以幫助我嗎?

即使我想再次這樣:

(function ($) { 

    var x = {"username":"lgangula"} 


    var manupulate = function(data){ 
     $.each(x, function(key,value){ 
      if(key === "username"){ 
       console.log(value);//consoling the name 
       var x = Handlebars.compile($("#header-template").html()); 
       console.log(x(value)); //no result here. 
          console.log(x({"username":"lgangula"})); //works fine 
      } 
     }) 
    } 

    manupulate(); 

})(jQuery); 

仍然沒有工作..

的情況下,如果我通過這樣的對象,它的工作原理..

console.log(x({"username":"lgangula"})); //works fine 
+0

let m e試試這個.. – 3gwebtrain

+0

我試過你說的方式,沒有運氣.. – 3gwebtrain

回答

1

你的避風港't render template try this,

var template = Handlebars.compile($("#header-template").html()); 
var html = template(x) 
console.log(html) 
+0

什麼是你的答案中的「x」?你能提供進一步的細節嗎? – 3gwebtrain

+0

'var x = {「username」:「lgangula」}' – Amar