Pass data to a dynamic template

我的未来我决定 提交于 2020-01-01 12:37:11

问题


With meteor updates up to 0.8 my old code stopped working.

Handlebars.registerHelper('getTemplate', function(id, context) {
    return Template[id](context);
}); 

<template name="main">
    ....
    {{{getTemplate templateName context}}}
    ....
</template>

//somewhere in other template 
Template.main.context = {name:value};

This way I was able to render a custom template with custom data. Now I can't find the way to pass context to the dynamic template. With blaze both templateName and context is undefined. Any advice?


回答1:


Meteor >= 0.8.2

You can use the UI.dynamic helper render a template with a context which are both specified dynamically. For more details, check out this issue.

Meteor < 0.8.2

Both of these issues are addressed on this page in the meteor wiki.

  1. Handlebars.registerHelper is now UI.registerHelper as seen here.

  2. Examples of how to dynamically render templates are shown here.


update

Actually, given the requirements, a solution doesn't seem very obvious to me. If you are willing to use session variables to set the template name and context, AND only have one dynamic template in your main template. You could do something like this:

<body>
  {{> main}}
</body>

<template name="main">
  {{> getTemplate context}}
</template>

<template name="dogs">
  <p>There are {{animals}} dogs!</p>
</template>

<template name="cats">
  <p>There are {{animals}} cats!</p>
</template>
Session.setDefault('templateName', 'dogs');
Session.setDefault('templateContext', {animals: 10});

Template.main.getTemplate = function() {
  return Template[Session.get('templateName')];
};

Template.main.context = function() {
  return Session.get('templateContext');
};



回答2:


This was brought up on the meteor-core list and @dgreensp, MDG core dev working on Blaze, opened Ticket #2007 - How to render a template to HTML with data so they definitely know about this and I'd expect a fix to land soon after 0.8.0.

He also included the following workaround:

var toHTMLWithData = function (kind, data) {
  return UI.toHTML(kind.extend({data: function () { return data; }}));
};

The github ticket has further discussion and alternate code snippets that you may find useful.



来源:https://stackoverflow.com/questions/22928333/pass-data-to-a-dynamic-template

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