我正在使用handlebars.js 为网页创建模板。到目前为止,我已经将一些数据存储在 JS 文件的数组中。然后将其呈现在 HTML 页面上。我正在使用 {{#each}} 循环遍历数组。这一切都工作正常并且渲染正确。
我使用 Bootstrap 3 作为框架。我想在显示 4 个内容 block 后跳出循环,并用另外 4 个内容 block 创建一个新行,依此类推。
我只是想知道最好的方法是什么。
到目前为止我的代码是
HTML:
<div class="container">
<div class="listings-nav row"></div>
<script id="listings-template" type="x-handlebars-template">
{{#each this}}
<div class="col-lg-3 listings">
<img class="" src="{{imgURL}}">
<span>{{genre}} / {{date}} {{#if age}} - <strong>{{age}}</strong>{{/if}}</span>
<a href="{{url}}"><h3>{{Event}}</h3></a>
<p>{{venue}}</p>
</div>
{{/each}}
</script>
</div>
JS:
$(function () {
var listingsData = [
{
age:45,
imgURL: 'http://placehold.it/300x200',
url: "http://www.google.com/",
Event:"Evening Classes for all @ Dancehouse",
venue:"Dancehouse, 1 Foley St, Dublin 1",
genre:"Dance",
date:"17.12.2013"
},
{
imgURL: 'http://placehold.it/300x200',
url: "http://www.google.com/",
Event:"Dublin Divided: September 2013",
venue:"Hugh Lane Gallery, Charelmout House, Parnel Square North, Dublin 1",
genre:"Theatre",
date:"17.12.2013"
},
{
imgURL: 'http://placehold.it/300x200',
url: "http://www.google.com/",
Event:"Leonora Carrington Exhibition",
venue:"Irish Museum of Modern Art, Kilmainham, Dublin ",
genre:"Art",
date:"17.12.2013"
},
{
imgURL: 'http://placehold.it/300x200',
url: "http://www.google.com/",
Event:"Sunday Theatre ensemble",
venue:"The Grand Social, Wellington Quay, Dublin 2",
genre:"Dance",
date:"17.12.2013"
},
{
imgURL: 'http://placehold.it/300x200',
url: "http://www.google.com/",
Event:"Dublin Divided: September 2013",
venue:"Hugh Lane Gallery, Charelmout House, Parnel Square North, Dublin 1",
genre:"Theatre",
date:"17.12.2013"
}
];
//Get the HTML from the template in the script tag
var theTemplateScript = $("#listings-template").html();
//Compile the template
var theTemplate = Handlebars.compile (theTemplateScript);
$(".listings-nav").append (theTemplate(listingsData));
});
非常感谢任何帮助
最佳答案
Handlebars 并不真正支持这一点,但您可以通过一个简单的循环来做到这一点:
for (var i = 0; i < listingsData.length; i += 4) {
$(".listings-nav").append(theTemplate(listingsData.slice(i, i + 4)));
}
关于javascript - 使用handlebars.js时创建新的 Bootstrap 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21606861/