0

I've been looking into single page apps and started with Marionette.js today. I found that the overall structure of the application is very effective (modules, events, etc) i can not get into idea how to use templates(views) to get most of them when using complicated data structures. i am used to handlebars-like templates that can do some additional logic and nesting.

What are the best practices to display nested templates?

Consider this not so complex data structure with nested data:

[{name:"John", addresses:
  [
    {street:"John Street",city:"New York, NY"},
    {street:"John Street",city:"Madrid, PA"}
  ],
  notes: [{note:"note1"},{note:"note2"}]
  },
  {name:"Alex", addresses:
  [
    {street:"Alex Street",city:"New York, NY"},
    {street:"Alex Street",city:"Madrid, PA"}
  ],
  notes: {}}
]

How to effectively render first-level array as table rows and inner arrays (like "addresses" and "notes") into individual columns in the row (in form of another table, for example).

4

3 回答 3

0

Marionette 提供了 Collection 和 CompositeViews 来呈现对象集合。使用 CompositeView 可以有效地渲染表格 请参阅 CompositeView 的文档-它有一个如何使用复合视图渲染表格的示例。

对于渲染复杂的嵌套结构,最好使用 Handlebars,因为它允许引用嵌套字段示例:{{x.y}}

于 2013-09-20T10:59:37.800 回答
0

如果你使用下划线,你可以这样做

<%= Marionette.Renderer.render('#your-template', {
    your: data,
    goes: here
}) %>

或者更好的例子是

<% _.each(someArrayOnModel, function(item) { %>
    <%= Marionette.Renderer.render('#templateForItem', item) %>
<% }); %> 
于 2013-09-20T20:02:05.317 回答
0

您可以使用CollectionView,您的数组将作为它的 传递给视图collection,然后您可以循环遍历addresses每一行以显示它们。

我不会为addresses数组的每个元素创建一个视图,因为不需要自己管理它们,它们将在显示主视图时显示(对吗?)。

所以你可以有这样的东西

NoUsers = Backbone.Marionette.ItemView.extend({
  template: "#no-users-template"
});

collection当传递为空时将使用它

User = Backbone.Marionette.ItemView.extend({});

这将定义如何呈现单个用户(您的顶级数组元素),您可以使用 Handlebars 进行addresses循环,例如

<div>
  {{ #each addresses }}
  <span>{{ street }} - {{ city }}</span>
  {{/each}}
</div>

Users = Backbone.Marionette.CollectionView({
  itemView: User,
  emptyView: NoUsers
});

这将定义它们如何一起发挥作用,有关详细示例,请参阅由 Marionette 的创建者 DErick Bailey 制作的示例应用程序。

于 2013-09-20T11:04:09.377 回答