【问题标题】:Meteor load template upon selection of dropdown list option选择下拉列表选项时流星加载模板
【发布时间】:2016-03-14 04:48:33
【问题描述】:

我有一个通过这个模板生成的下拉列表,位于ranvas.html

<template name="shape-dropdown">
    <select id = "shape-select">
        <option value = "none">select a shape</option>
        {{#each shape in shapes}}
            <option value = "{{this}}"> {{this}} </option>
        {{/each}}
    </select>
</template>

它从ranvas.js 中的帮助器获取形状名称:

 Template.shape-dropdown.helpers({
      shapes: [
          { shapetype: "random line"},
          { shapetype: "random quadratic curve"},
          { shapetype: "random bezier curve"},
          { shapetype: "random arc"},
          { shapetype: "random stroke triangle"},
          { shapetype: "random fill triangle"},
          { shapetype: "random stroke rectangle"},
          { shapetype: "random fill rectangle"}
          { shapetype: "random stroke circle"},
          { shapetype: "random fill circle"},
      ]
  });

选择其中一种形状时,我希望一个位于 shape-templates.html中的模板加载。 For example when the "random line" option is selected, I want this template to load:

<template name="rand_line">
   <label>x1: <input type="text"> - <input type="text"></label>
   <label>y1: <input type="text"> - <input type="text"></label>
   <label>x2: <input type="text"> - <input type="text"></label>
   <label>y2: <input type="text"> - <input type="text"></label>
   {{> rand_strokeStyle}}
</template>

【问题讨论】:

  • 您可以将 Dynamic 模板助手与从下拉列表的 change 事件处理程序设置的反应变量一起使用。
  • 你在使用 Iron Router 吗?
  • @StefanL19 不,我不是
  • 你尝试过使用 Sessions 吗?

标签: javascript templates meteor


【解决方案1】:

你会想要使用dynamic templates

{{> Template.dynamic template="rand_line"}}

如果您扩展 .shape-dropdown.helpers,您可以跟踪每个形状的 1:1 匹配模板,例如:

Template.shape-dropdown.helpers({
  shapes: [
    { shapetype: "random line", template: "rand_line"},
    ...
  ]
});

您需要一个事件处理程序来跟踪选择:

Template.shape-dropdown.events({
  'change #shape-select": function(ev){
  var tpl = shapes.filter(function ( obj ) {
    return obj.shape === $('#shape-select').val();
  })[0].template;
  Session.set('template',tpl)
  }
});

当然,您仍然需要一个帮助器来将该会话变量的值作为动态帮助器的参数输入到您的 blaze 模板中。

【讨论】:

  • 如何根据选项更改模板?我会使用{{#let}} 并有一个变量指向帮助程序中的模板对象吗?
  • 您需要一个事件处理程序来更新会话变量或反应变量,并让动态模板指向它。我会补充答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
相关资源
最近更新 更多