Nam*_*mbi 15 javascript jquery templates backbone.js underscore.js
模板看起来像这样.
<div>
<H5>Status for your request</H5>
<table>
<tbody>
<tr>
<th>RequestId</th>
<th><%=id%></th>
</tr>
<tr>
<th>Email</th>
<th><%=emailId%></th>
</tr>
<tr>
<th>Status</th>
<th><%=status%></th>
</tr>
</tbody>
</table>
</div>
Run Code Online (Sandbox Code Playgroud)
这是呈现页面的View Javascript.
window.StatusView = Backbone.View.extend({
initialize:function () {
console.log('Initializing Status View');
this.template = _.template(tpl.get('status'));
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
},
events: { "click button#status-form-submit" : "getStatus" },
getStatus:function(){
var requestId = $('input[name=requestId]').val();
requestId= $.trim( requestId );
var request = requests.get( requestId );
var statusTemplate = _.template(tpl.get('status-display'));
var statusHtml = statusTemplate( request );
$('#results-span').html( statusHtml );
}
});
Run Code Online (Sandbox Code Playgroud)
当单击输入时,将读取requestId并将状态附加到id为'results-span'的html元素中.
使用变量值替换html-template中的值时会发生故障.
var statusTemplate = _.template(tpl.get('status-display'));
var statusHtml = statusTemplate( request );
Run Code Online (Sandbox Code Playgroud)
渲染失败,出现以下错误.
Uncaught ReferenceError: emailId is not defined
(anonymous function)
_.templateunderscore-1.3.1.js:931
window.StatusView.Backbone.View.extend.getStatusstatus.js:34
jQuery.event.dispatchjquery.js:3242
jQuery.event.add.elemData.handle.eventHandle
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 22
下划线_.template:
将JavaScript模板编译为可以评估渲染的函数.
[...]Run Code Online (Sandbox Code Playgroud)var compiled = _.template("hello: <%= name %>"); compiled({name : 'moe'}); => "hello: moe"
所以基本上,你将模板函数交给一个对象,模板在该对象中查找你在模板中使用的值; 如果你有这个:
<%= property %>
Run Code Online (Sandbox Code Playgroud)
在模板中,您将模板函数调用为t(data),然后模板函数将查找data.property.
通常将视图的模型转换为JSON并将该对象移交给模板:
render: function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
Run Code Online (Sandbox Code Playgroud)
我不知道你的eventName是什么或者你打算用它做什么,但你需要得到一个具有这种结构的对象:
data = { id: '...', emailId: '...', status: '...' }
Run Code Online (Sandbox Code Playgroud)
从某处并将其交给模板功能:
var html = this.template(data)
Run Code Online (Sandbox Code Playgroud)
获取一些HTML放在页面上.
演示(用于说明目的的假模型):http://jsfiddle.net/ambiguous/hpSpf/