Fastest way to check whether the cursor returned b

2019-08-12 18:29发布

问题:

I often do something like this, using the items helper twice:

{{#if items}}
<h1>Items</h1>
  {{#each items}}
    {{> item}}
  {{/each}}
{{/if}}

Template.foo.helpers
  items: ->
    Items.find 
      bar: true
    , 
      sort: created: -1
      transform: (item) ->
        i.good = true
        i

Is Meteor doing extra work in this scenario? Would it be more efficient to switch the if to use something like areItems?

areItems: ->
  Items.find
    bar: true
  .count() > 0

回答1:

In the template, you can use {{#with items}} and then either 'this.count' or 'this.length' to check whether your helper returned any items.

Use this.count if 'items' is a cursor, e.g. the result of a find() operation:

{{#with items}}
  {{#if this.count}}
    <h1>Items</h1>
    {{#each this}}
      {{> item}}
    {{/each}}
  {{/if}}
{{/with}}

Use this.length if 'items' is an array:

{{#with items}}
  {{#if this.length}}
    <h1>Items</h1>
    {{#each this}}
      {{> item}}
    {{/each}}
  {{/if}}
{{/with}}


回答2:

You can use {{else}}

{{#each this}}
   {{> item}}
{{else}}
   <h1>No Items</h1>   
{{/each}}


回答3:

Use #with, #if this.length, and .fetch:

{{#with items}}
  {{#if this.length}}
  <h1>Items</h1>
    {{#each this}}
      {{> item}}
    {{/each}}
  {{/if}}
{{/with}}

Template.foo.helpers
  items: ->
    Items.find 
      bar: true
    , 
      sort: created: -1
      transform: (item) ->
        i.good = true
        i
    .fetch()


回答4:

You can do what you want using spacebars' #with block tag.

Like this:

{{#with items}}
  {{#if this.count}}<h1>Items</h1>{{/if}}
  {{#each this}}
    {{> item}}
  {{/each}}
{{/with}}

The block tag is documented here. The relevant quote is:

If the argument to #with is falsy (by the same rules as for #if), the content is not rendered.


update: fixed code for desired behaviour. Also while my example demonstrates making one helper call it is better practice to make an 'itemList' template and include it by using {{> itemList items}}.



回答5:

I found that simply {{#if items.count}} was sufficient.

{{#if items.count}}
  <h2>Below there are items</h2>
{{/if}}

{{#each items}}
  <div class="item-name">{{this.name}}</div>
{{else}}
  <h2>There are no items</h2>
{{else}}