且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据集合的大小制作模板条件?

更新时间:2023-11-02 13:22:04

这是正确的方法:

 < template name =list> 
< ul>
{{#each items}}
< li> {{itemContents}}< / li>
{{else}}
< li class =placeholder>此列表中没有项目。< / li>
{{/ each}}
< ul>
< / template>

有关详细信息,请参阅 handlebarsjs.com

(流星使用 Spacebars ,它的灵感来自Handlebars,所以Syntax几乎相同。)


I want to do something like this:

<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>

where items is a Meteor.cursor:

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

However, the code above doesn't work, as the conditional will evaluate positively even if there are no items (which is mildly surprising because Handlebars evaluates [] as falsey). I tried changing the condition to

{{#if items.count}}

but then I get the cryptic error

Unknown helper 'items'

So, is there a way to write such a condition within a meteor Handlebars template?

This would be the correct way to go:

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

For further information take a look at handlebarsjs.com.

(Meteor uses Spacebars which is inspired by Handlebars. So the Syntax is almost the same.)