0

I'm creating a Meteorite package that renders a table for a specific collection. I want this table to be customizable by adding optional custom columns as a templates:

<template name="myPluginTable">
  <table>
    <thead>
      <th>Column 1</th>
      <th>Column 2</th>
      {{> customHeaders}}
    </thead>
    <tbody>
      {{#each objects}}
        <tr>
          <td>{{firstValue}}</td>
          <td>{{secondValue}}</td>
          {{> customFields}}
        </tr>
      {{/each}}
    </tbody>
  </table>
</template>

Now this works fine as long as templates customHeaders and customFields are specified somewhere in the app.

But if these templates are omitted, an error is thrown. This cannot be circumvented by adding dummy templates to the package either, as trying to overwrite them raises an error as well.

The solution that I came up with:

Template.myPluginTable.helpers({
  customHeadersExist: function() {
    return typeof(Template.customHeaders) === "object";
    },
  customFieldsExist: function(user) {
    return typeof(Template.customFields) === "object";
  },
});

And in the templates:

{{#if customHeadersExist}}
  {{> customHeaders}}
{{/if}}

and

{{#if customFieldsExist}}
  {{> customFields}}
{{/if}}

Now this works, but the solution seems overtly complicated for such a simple task - do I really need to declare helper functions for each of the optional templates? So my question really is:

What is the best way to make a package customization template optional? Is it this, or is there a better way?

4

1 回答 1

4

我想到的最简单的解决方案是实现自定义助手:

UI.registerHelper('safeRender', function () {
  var component = Template[this.name];
  if (component) {
    return component.extend({data: this.data});
  }
  return UI.Component;
});

您可以像这样在模板中使用它:

{{> safeRender name='customHeaders' data=.}}

data=.部分用于确保模板将在相同的数据上下文中呈现。

于 2014-04-02T19:10:44.200 回答