Fastest way to check whether the cursor returned by a template helper is empty?

做~自己de王妃 提交于 2019-12-13 02:10:19

问题


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


来源:https://stackoverflow.com/questions/27762610/fastest-way-to-check-whether-the-cursor-returned-by-a-template-helper-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!