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?

3 Answers 3

32

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

2
  • shouldn't OP's code work if he declared items like this: Template.list.helpers({ items: function() { return Items.find() } };
    – rdk1992
    Mar 2, 2016 at 15:28
  • I don't think so. The problem that he was running into was that [] !== false
    – HaNdTriX
    Mar 2, 2016 at 17:31
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}}.

5

I have been evaluating Handlebars for the past few weeks and I had a similar issue. What worked for me was reading the length property and adding the else tag.

    {{#if competitions.length}}
        <div class="game-score span-4"> 
        ...code goes here...    
        </div>
   {{else}}
        {{> allGameNotes}}
   {{/if}
1
  • That doesn't work for me. I get the same error as I do when I try to use count. In this case, it would be Unknown helper 'competitions'. Jun 14, 2012 at 22:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.