【问题标题】:How to create reusable UI with variable template?如何使用可变模板创建可重用的 UI?
【发布时间】:2016-11-15 01:23:50
【问题描述】:

我想做这样的事情:

组件文件:

<template name="drop_down">
    <span class="dropdown">
        {{> primary_element}} <--- load the template named button
        <span class="dropdown-panel">
            {{> panel_template}} <--- load the template named button_panel
        </span>
    </span>
</template>

用法:

{{> drop_down primary_element="button" panel_template="button_panel"}}
<template name="button"> some styled button </template>
<template name="button_panel"> panel content </template>

然后我可以像这样重复使用它

{{> drop_down primary_element="tmp_btn_2" panel_template="tmp_panel_2"}}
    <template name="tmp_btn_2"> another button style </template>
    <template name="tmp_panel_2"> other panel content </template>

【问题讨论】:

  • 它将作为数据变量传入模板。

标签: meteor spacebars


【解决方案1】:

您应该可以使用dynamic templates 执行此操作。在 blaze 中,您可以传入要用作变量的模板以及数据上下文本身。它们非常灵活。

例如:

{{> Template.dynamic template=whichTemplate data=myData }}

这将引用whichTemplate 帮助器来确定要使用的模板,并从myData 帮助器获取数据上下文。即模板的选择和数据的选择都来自变量

在您的情况下,您尝试在 dropdown 模板的上下文中使用两个动态模板。你可以这样做:

<template name="drop_down">
  {{#with myElements}}
    <span class="dropdown">
      {{> Template.dynamic template=this.primary}}
      <span class="dropdown-panel">
        {{> Template.dynamic template=this.panel}}
      </span>
    </span>
{{/with}}
</template

那么您的myElements 助手只需要返回模板的名称以用作字符串,例如:

Template.dropdown.helpers({
  myElements() {

    let p1 = "button";  // compute these two based on your own logic
    let p2 = "button_panel";

    return {primary: p1, panel: p2 };
  }
});

【讨论】:

  • 你能举个例子吗?
  • 谢谢你,这就是我想要的,但在 myElement 中它应该返回 ||主要:this.primary_element,面板:this.panel_template ||所以我可以动态使用它。
  • 是的,这就是将它放在函数中的意义所在,你可以返回任何你需要的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 2014-08-26
  • 2022-10-08
  • 2011-08-28
相关资源
最近更新 更多