2014-01-29 229 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