我使用的是Underscore模板.可以附加外部文件作为模板吗?
在Backbone View中我有:
textTemplate: _.template( $('#practice-text-template').html() ),
initialize: function(){
this.words = new WordList;
this.index = 0;
this.render();
},
Run Code Online (Sandbox Code Playgroud)
在我的HTML中是:
<script id="practice-text-template" type="text/template">
<h3>something code</h3>
</script>
Run Code Online (Sandbox Code Playgroud)
它运作良好.但我需要外部模板.我尝试:
<script id="practice-text-template" type="text/template" src="templates/tmp.js">
Run Code Online (Sandbox Code Playgroud)
要么
textTemplate: _.template( $('#practice-text-template').load('templates/tmp.js') ),
Run Code Online (Sandbox Code Playgroud)
要么
$('#practice-text-template').load('templates/tmp.js', function(data){ this.textTemplate = _.template( data ) })
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
在玩了AMD/RequireJS后,我想知道加载包含模板和CSS的UI模块是否是一个好主意,这样它们就完全独立于网页.
这听起来不错,但我没有看到这在野外实施,所以可能存在陷阱.
想想一些具有以下结构的UI模块:
myWidget
|--img
|--main.js
|--styles.css
+--template.tpl
Run Code Online (Sandbox Code Playgroud)
一个文件夹中的所有内容.看起来很不错.
main.js中的模块看起来像这样:
define(["TemplateEngine", "text!myWidget/template.tpl"], function(TemplateEngine, template) {
// Load CSS (Pseudo Code)
var cssUrl = "myWidget/styles.css";
appendToHead(cssUrl);
return function() {
return {
render: function(data) {
return TemplateEngine.toHtml(template, data);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
现在的问题是:
我打算使用backbone.js和underscore.js来创建网站,我将有很多下划线模板:
<script type="text/template" id="search_template">
<p id="header">
//header content will go here
</p>
<p id="form">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</p>
<p id="dynamic_date">
//dynamic data will be displayed here
</p>
</script>
Run Code Online (Sandbox Code Playgroud)
当然,我的模板会复杂得多.
由于我将拥有大量的内容,因此我不希望每次加载页面时都加载所有模板.我想找到一个解决方案,我只能在使用它时加载特定模板.
另一件事是,我的大多数模板将具有相同的结构,只<p id="form"></p>和<p id="dynamic_date"></p>内容会有所不同.
你能告诉我怎么办?
谢谢,