【问题标题】:Create/modify Meteor templates at runtime在运行时创建/修改 Meteor 模板
【发布时间】:2015-03-06 04:13:08
【问题描述】:

我想知道如何解决这个问题:

我有一个模板,其中包含一些文本和一些模板助手:

<template>Hello {{who}}, the wheather is {{weather}}</template>

现在我需要在运行时动态更改模板的内容,同时保持辅助功能。例如,我需要这样:

<template>Oh, the {{weather}}. Good evening {{who}}</template>

文本发生变化,并且在不同的位置需要助手。考虑一个应用程序,用户可以在其中创建自定义表单,其中包含某些变量的占位符,例如填写表单的用户名。基本上,模板的内容存储在一个mongo文档中,需要在运行时转成模板,或者需要更改现有的模板。

如何解决这个问题?我可以在运行时更改模板的内容吗?

【问题讨论】:

  • 模板的内容是否可以像你的例子一样总是用字符串表示,还是可以包含其他html元素、子模板等?
  • 在我的用例中,它可以包含文本和 html,但没有子模板。除了助手之外没有动态的东西。
  • 您尝试过服务器端渲染吗?这可能是一个不错的选择。在客户端上,可以在运行时创建模板,执行类似github.com/looshi/Meteor-Live-Template-Editor/blob/master/… 的操作。不过,我不知道如何将作用域助手分配给模板,只知道全局作用域助手。这是一个工作演示,您可以在运行时编辑这些模板live-template-editor.meteor.com/FjkeyHE94KvooDHeS
  • 谢谢,看起来不错!会试试的。

标签: meteor meteor-blaze


【解决方案1】:

要解决此用例,您需要使用两种技术。

首先,您需要能够更改模板响应式。为此,您可以使用Template.dynamic。例如:

{{> Template.dynamic template=helperToReturnName [data=data] }} 

请看这里:http://docs.meteor.com/#/full/template_dynamic

现在您可以更改模板,您需要能够根据您的数据库内容动态创建新模板。这并非易事,但如果您愿意编写代码来创建它们,这是可能的,如下所示:

Template.__define__("postList", (function() {
  var view = this;
  return [
    HTML.Raw("<h1>Post List</h1>\n  "),
    HTML.UL("\n    ", Blaze.Each(function() {
      return Spacebars.call(view.lookup("posts"));
    },
    function() {
      return [ "\n      ", HTML.LI(Blaze.View(function() {
        return Spacebars.mustache(view.lookup("title"));
      })), "\n    " ];
    }), "\n  ")
  ];
}));

代码 sn-p 取自 Meteorhacks 上的 this article,文章本身更详细。阅读本文后,您将掌握完成任务所需的知识...

【讨论】:

    【解决方案2】:

    只要有一个助手动态构建整个字符串(记住 this 指的是当前数据上下文):

    Template.foo.helpers({
      dynamicString: function(switch){
        if ( switch == 1) return "Hello "+this.who+", the wheather is "+this.weather;
        else return "Oh, the "+this.weather+". Good evening "+this.who;
      }
    });
    

    然后在你的模板中:

    <template name="foo">
      {{dynamicString}}
    </template>
    

    或者,只需使用 {{#if variable}} 或 {{#unless variable}} 块来更改模板中的逻辑。简单得多。

    <template name="foo">
      {{#if case1}}
        Hello {{who}}, the wheather is {{weather}}
      {{else}}
        Oh, the {{weather}}. Good evening {{who}}
      {{/if}}
    </template>
    

    您总是可以有一个模板助手来计算必要的布尔变量(例如 case1)。

    【讨论】:

    • 但是谁和天气不在上下文中,他们是模板的帮手。
    猜你喜欢
    • 2015-01-28
    • 2013-04-09
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多