How do I iterate over an unknown object in a Meteor Spacebars template?

大憨熊 提交于 2019-12-13 06:39:23

问题


So I have a Meteor Collection. Each object/document in that collection can have an unknown structure. That is to say, I don't know the name of each property, nor how many there are, until runtime.

Essentially, each object in the collection is created from arbitrary data people provide via my front-end page (via CSV upload, which works fine). So I don't initialize the collection when Meteor starts.


Now I'd like to create a table in my HTML page, that renders the collection, but without me pre-defining how many columns are needed and what their names are.

So how do I set the number and names of the columns in my Spacebars/HTML template dynamically?

So here's how far I've got on the template side:

<table>
    {{#each rows}}
      {{> row}}
    {{/each}}
</table>

...and the template:

<template name="row">
    {{#if header}}  <!-- header is explicitly set, so this is fine -->
      <th>
        {{#each WHAT?}}
          <td>{{???}}</td>
        {{/each}}
      </th>
    {{else}}
      <tr>
        {{#each WHAT?}}
          <td>{{???}}</td>
        {{/each}}
      </tr>
    {{/if}}
</template>

I tried finding any reference in Spacebars and Blaze documentation, but all examples always require me to know the names of the columns from the get-go.

Any ideas?

Edit: Here's an example object, which I am explicitly identifying as the header via the header property:

...and "rows" look like this:

So I lied apparently, in that my property/column names are always index numbers.

To answer another question: Once the data set is determined (the collection populated), all objects have the same number of properties (i.e. imagine a csv table, which is where my data will always come from).


回答1:


From a mongo db data modeling pov this design can be readily improved by sticking your variable fields into arrays. i.e.

{ items:
  [
    "wexfr",
    "123x",
    "ewfxc",
    "rgc"
  ],
  _id: "NYz84Qhu901MPab",
  header: false,
  createdAt: "2015-04-08T19:46:24"
}

Then you can have templates such as:

{{#each row}}
  {{#each items}}



回答2:


Since your properties have no value except for an index, it's not really a good use case for objects. If you HAD to stick with the schema (or do deeply nested updates, although I'm not sure how you could...), follow Christian's suggestion. Otherwise, I'd get the front-end to give you arrays OR convert your objects to arrays in a post-process.

data = [['uno', 'dos', 'tres'], ['wexfd', 'foobar', 'etc.']]

Then, you could nest the each helpers and access the primitives with this. Super clean & easy.



来源:https://stackoverflow.com/questions/29515497/how-do-i-iterate-over-an-unknown-object-in-a-meteor-spacebars-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!