我正在开发一个带有主干和车把的应用程序,用于我所在城市的公交车时刻表。一站式的模式是:
define(["jquery", "underscore", "backbone"],
function ($, _, Backbone){
var stop = Backbone.Model.extend({
defaults : {
id : "23",
lon : "43,465187",
lat : "-80,522372",
listabus : ["80", "83", "106"]
}
});
return stop;
});其中"Listabus“是在23号车站附近经过的所有公共汽车的列表。我不知道如何在template...help me中循环数组!:D谢谢建议
发布于 2013-11-18 22:30:58
这是您的html:
<!-- below is your template !-->
<script id="bus-stops" type="text/x-handlebars-template">
<ul>
{{#each stops}}
<li>{{this}}</li>
{{/each}}
</ul>
</script>
<!-- result container !-->
<div id="result"></div>和js代码
var BusStop = Backbone.Model.extend(),
busStop = new BusStop({stops: ['a', 'b', 'c']});
template = $('#bus-stops').html(),
compiler = Handlebars.compile(template),
html = compiler({stops: busStop.get('stops')});
$('#result').html(html);抱歉,jsfiddle不能与把手一起工作
发布于 2013-11-18 08:34:39
你只需要把你的模型属性作为一个对象传递给下划线模板函数。第一个参数是模板,第二个参数是您的数据。您可以传入任何对象数据,但由于显而易见的原因,下划线在model.toJSON()中发挥得非常好。
this.$('#insertWherever').html(_.template($('#busList'), stopModel.toJSON()));你的模板应该是这样的。
<script id="busList" type="text/html">
<ul>
<% _.each(listabus, function(busNumber){ %>
<li><%= busNumber %></li>
<% }); %>
</ul>
</script>总而言之,<% %>是一种转义和运行任意JS代码的方法。<%= %>是一种将内容插入或输出到模板中的方法。
请参阅http://underscorejs.org/#template和http://underscorejs.org/#each
如果你使用的是require.js,你可以下载一个叫做text的插件!
这允许您在依赖项中定义HTML文件,并让模板驻留在它们自己的单独文件中。这与上面的方法相反,上面的方法使用嵌入的脚本标记和jquery从您正在处理的任何视图中获取模板。
查看插件/ text @ http://requirejs.org/docs/download.html
https://stackoverflow.com/questions/20036961
复制相似问题