2014-01-29 78 views
0

我試圖使用腳本標記將文件中的模板加載到HTML文件中。我想用這個作爲UnderscoreJS模板 - 但我不能夠加載該文件:在HTML中加載下劃線模板

//main.js 

    this.template = _.template($("#add-question").html()); 
      console.log("testing"); 
      console.log(this.template({ 
       question: "How are you doing?", 
       yesOrNo: true 
      })) 

//console output: 

    testing  Main.ts:37 
       Main.ts:38 


    //main html file: 

    <html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html"> 
    <head> 
     <script type="text/template" id="add-question" src="client/add-new-question.html"></script> 
    </head> 
    <body> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> 
    <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js" type="text/javascript"></script> 
    <script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script> 
    <script data-main="main.js" src="build/require.js"></script> 

    </body> 
    </html> 

//客戶端/附加新question.html

<form id="testForm"> 
     <span>"<% question %></span> 
     <input id="questionInput" type="text"> 
     <span>"<% yesOrNo %></span> 
     <input id="typeInput" type="checkbox"> 
    </form> 

更新: 這裏是更新的HTML中,我嘗試加載HTML,但通過腳本標記在正文中。仍然不起作用。這是在使用UnderscoreJS呈現模板時預期完成的方式。我希望能夠使用requireJS加載模板,但使用underscoreJS模板函數進行渲染。

<body> 
<script type="text/template" id="add-question"> 
    <form id="testForm"> 
     <span>"<%= question %></span> 
     <input id="questionInput" type="text"> 
     <span>"<%= yesOrNo %></span> 
     <input id="typeInput" type="checkbox"> 
    </form> 
</script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script> 
<script src="https://rawgithub.com/jashkenas/underscore/master/underscore-min.js"></script> 
<script data-main="main.js" src="build/require.js"></script> 
</body> 
+0

嗨嘗試<%= %>代替<% %>。 – 5122014009

+0

@Sayuri嘗試過。相同的結果 – EternallyCurious

回答

0

您必須使用<%=來輸出變量而不是<%

它看起來像你正在使用requirejs。
所以,你也可以使用第三方物流的延伸和存儲您的下劃線模板.tpl文件:

https://github.com/ZeeAgency/requirejs-tpl

define(['tpl!client/add-new-question.html'], function(tpl) { 

     console.log(tpl({ 
      question: "How are you doing?", 
      yesOrNo: true 
     })); 

}); 

鏈接:
How to use underscore.js as a template engine? underscore.js

+0

我想使用requireJs加載模板,但Underscore來渲染它們。我怎麼做?其次,我使用的是用Underscore加載太陽穴的方法,但它不起作用。請參閱問題中的更新。 – EternallyCurious

+0

tpl擴展已經在使用underscorejs的模板引擎 – jantimon

+0

我得到「Uncaught ReferenceError:define is not defined」。我們可以使用「require」而不是「define」嗎? – EternallyCurious