我有一个使用 Backbone/Marionette/Mustache 渲染良好的集合。
所以 PersonModel
和 PersonView
工作正常。 PersonView
有一个名为 PersonTemplate
的 mustache 模板,它由我的 PeopleCollection
和 PeopleCollectionView
完美加载,并在默认值内呈现标签名:“div”
。
但是,我想在另一个模板中渲染这个集合,这样我就可以在那里放置一些标题。
现在本质上是:
<div> <!-- collection tagName -->
<div class="person"> <!-- PersonTemplate -->
<div class="person-name">John</div>
</div>
<div class ="person"> <!-- PersonTemplate -->
<div class="person-name">Dave</div>
</div>
</div>
但我希望它是:
<div id="people> <!-- CollectionTemplate -->
<h1>People</h1> <!-- CollectionTemplate -->
<div class="person"> <!-- PersonTemplate -->
<div class="person-name">John</div>
</div>
<div class ="person"> <!-- PersonTemplate -->
<div class="person-name">Dave</div>
</div>
</div>
我知道我可以在事后使用 jQuery 添加这些项目,但我希望避免这种情况,因为我实际的 CollectionTemplate
比此处给出的示例复杂得多。
最佳答案
CompositeView 正是您所需要的。以下是我为简单笔记面板设置 CompositeView 的方法。
每个笔记的项目 View :
View.NoteRow = Marionette.ItemView.extend({
template: Handlebars.compile(rowTemplate),
tagName: "tr",
className: "row-item",
})
综合 View :
View.NotesPanel = Marionette.CompositeView.extend({
template: Handlebars.compile(panelTemplate),
itemView: View.NoteRow,
itemViewContainer: "tbody",
className: "panel panel-default button-panel notes-panel",
events: {
"click button#add-note" : "addNote"
}
})
现在是模板:
面板模板:
<div class="panel-heading">
<div class="container-fluid">
<div class="row ">
<div class="col-md-6 col-lg-9">
<h3 class="panel-title"><i class="fa fa-pencil"></i> Notes</h3>
</div>
<div class="col-md-6 col-lg-3 button-column">
<a href="#"><button id="add-note" class="btn btn-xs btn-success"><i class="fa fa-plus"></i> Add Note</button></a>
</div>
</div>
</div>
</div>
<div class="panel-body">
<table id="notes-table" class="table">
<thead>
<tr>
<th>User</th>
<th>Note</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
行模板:
<td>{{employee_id}}</td>
<td>
<p>{{note_text}}</p>
<p><span class="tooltip-span timestamp" id="account-created" data-toggle="tooltip" title="{{created_at}}">{{humanize created_at}}</span></p>
</td>
在您的 CompositeView 定义中,您指定要在我的示例中使用的模板 (panelTemplate)。您可以指定复合 View 所包含的集合中的每个模型要使用哪个 ItemView。 (在我的示例中为 View.NoteRow)。比您在模板中定义每个 ItemView 将进入的容器(我的每个 ItemView 都进入)
关于javascript - Backbone/Marionette CollectionView - 在模板内渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24049169/