【问题标题】:How do I make a template conditional based on a collection's size?如何根据集合的大小制作有条件的模板?
【发布时间】:2015-09-07 13:17:30
【问题描述】:

我想做这样的事情:

<template name="list">
  <ul>
  {{#if items}}
      {{#each items}}
        <li>{{itemContents}}</li>
      {{/each}}
  {{else}}
    <li class="placeholder">There are no items in this list.</li>
  {{/if}}
  <ul>
</template>

items 是 Meteor.cursor:

Template.list.items = function() {
  return Items.find();
};

但是,上面的代码不起作用,因为即使没有项目,条件也会积极评估(这有点令人惊讶,因为 Handlebars 将 [] 评估为错误)。我尝试将条件更改为

{{#if items.count}}

然后我得到了一个神秘的错误

Unknown helper 'items'

那么,有没有办法在流星把手模板中编写这样的条件?

【问题讨论】:

    标签: meteor handlebars.js


    【解决方案1】:

    这是正确的方法:

    <template name="list">
      <ul>
      {{#each items}}
        <li>{{itemContents}}</li>
      {{else}}
        <li class="placeholder">There are no items in this list.</li>
      {{/each}}
      <ul>
    </template>
    

    如需了解更多信息,请查看handlebarsjs.com。

    (Meteor 使用受 Handlebars 启发的Spacebars。所以语法几乎相同。)

    【讨论】:

    • 如果他声明这样的项目,OP 的代码不应该工作:Template.list.helpers({ items: function() { return Items.find() } };
    • 我不这么认为。他遇到的问题是[] !== false
    【解决方案2】:

    通过使用with 更改评估上下文,我能够让我的模板正常工作:

    <template name="list">
      <ul>
      {{#with items}}
        {{#if count}}
            {{#each this}}
              <li>{{itemContents}}</li>
            {{/each}}
        {{else}}
          <li class="placeholder">There are no items in this list.</li>
        {{/if}}
      {{/with}}
      <ul>
    </template>
    

    注意修改后的表达式{{#if count}} 和{{#each this}}。

    【讨论】:

      【解决方案3】:

      过去几周我一直在评估 Handlebars,遇到了类似的问题。对我有用的是读取长度属性并添加 else 标签。

          {{#if competitions.length}}
              <div class="game-score span-4"> 
              ...code goes here...    
              </div>
         {{else}}
              {{> allGameNotes}}
         {{/if}
      

      【讨论】:

      • 这对我不起作用。当我尝试使用count 时,我遇到了同样的错误。在这种情况下,它将是 Unknown helper 'competitions'.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      • 2017-06-21
      • 2011-08-21
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      相关资源
      最近更新 更多