【问题标题】:Iteratively generate a template containing handlebars (spacebars)迭代生成包含把手(空格键)的模板
【发布时间】:2015-10-28 22:24:07
【问题描述】:

所以为了简单起见,最终的模板需要如下所示:

<template name="Profile">
  <h1> This is a profile view </h1>
  <h4>Username</h4>
  <p>{{username}}</p>
  <h4>Name</h4>
  <p>{{name}}</p>
  <h4>Email:</h4>
  <p>{{email}}</p>
</template>

对应的助手如下:

Template.Profile.helpers({
  username: function() {
    return this.username;
  },
  email: function() {
    return this.emails[0].address;
  },
  name: function() {
    return this.profile.name;
  }
});

现在,随着新字段的添加,此模板将继续增长,为了保持代码简洁,我尝试将模板分成两个,如下所示:

<template name="Profile">
  <h1> This is a profile view </h1>
  {{#each items}}
    {{> Section}}
  {{/each}}
</template>

<template name="Section">
  <h4>{{label}}</h4>
  <p>{{ {{id}} }}</p>
</template>

并且新模板有这个对应的助手:

Template.Section.helpers({
  items: function() {
    var fields = [
      {label: "Username", id="username"},
      {label: "First Name", id="name"},
      {label: "Email Address", id="email"}
    ];
    return fields;
  }
});

主要是Sections 模板中的那个位,我试图以某种方式嵌套空格键:&lt;p&gt;{{ {{id}} }}&lt;/p&gt;

我正在尝试的效果是,这些部分都迭代地组合到 Profile 模板中,然后看到 {{name}}{{email}},然后 Profile 助手填充该字段。

这有可能吗?

【问题讨论】:

    标签: templates meteor spacebars


    【解决方案1】:

    您的解决方案非常接近 - 您只需要从您的助手返回一组反应数据。试试这个:

    Template.Profile.helpers({
      sections: function() {
        return [
          {label: 'username', data: this.username},
          {label: 'email', data: this.emails[0].address},
          {label: 'name', data: this.profile.name}
        ];
      }
    });
    
    <template name="Profile">
      <h1>This is a profile view</h1>
      {{#each sections}}
        {{> section}}
      {{/each}}
    </template>
    
    <template name="section">
      <h4>{{label}}</h4>
      <p>{{data}}</p>
    </template>
    

    【讨论】:

    • 谢谢 :) 只是为了比较,关于是否可以使用 Template.parentData() 实现这一点的任何想法?
    • 我想你可以这样做,但它让我觉得更尴尬有两个原因:(1)我希望我的模板尽可能独立以实现可维护性和可重用性 - 任何时候你混合你的通过访问另一个模板的数据,您会丢失其中的一些数据(当然,有时这是必要的)。 (2) 如果父母持有用户,您仍然必须将用户对象中的路径传递给每个子模板,或者每个子模板都知道如何根据标签访问值 - 这感觉没有必要详细。
    • 很公平......无论如何,最初的解决方案效果很好。 :)
    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 2015-10-10
    • 2015-08-27
    • 1970-01-01
    相关资源
    最近更新 更多