如何根据集合的大小创建模板条件?

Tre*_*ham 14 handlebars.js meteor

我想做这样的事情:

<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>
Run Code Online (Sandbox Code Playgroud)

itemsMeteor.cursor 在哪里:

Template.list.items = function() {
  return Items.find();
};
Run Code Online (Sandbox Code Playgroud)

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

{{#if items.count}}
Run Code Online (Sandbox Code Playgroud)

但后来我得到了神秘的错误

Unknown helper 'items'
Run Code Online (Sandbox Code Playgroud)

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

HaN*_*riX 32

这将是正确的方法:

<template name="list">
  <ul>
  {{#each items}}
    <li>{{itemContents}}</li>
  {{else}}
    <li class="placeholder">There are no items in this list.</li>
  {{/each}}
  <ul>
</template>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看handlebarsjs.com.

(Meteor使用受Handlebars启发的Spacebars.因此语法几乎相同.)


Tre*_*ham 10

通过使用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>
Run Code Online (Sandbox Code Playgroud)

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


小智 5

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

    {{#if competitions.length}}
        <div class="game-score span-4"> 
        ...code goes here...    
        </div>
   {{else}}
        {{> allGameNotes}}
   {{/if}
Run Code Online (Sandbox Code Playgroud)