Alex Rivera | Logout

How do I make a template conditional based on a collection's size?

Asked 2012-06-14T20:16:51.493
14

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?

Edit
Report

1 Answer

10

I was able to get my template to work by using with to change the evaluation context:

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

Notice the modified expressions {{#if count}} and {{#each this}}.

answered 2012-06-14T22:48:32.013

Your Answer