Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 627
Trevor Burnham Avatar asked Jun 14 '12 20:06

Trevor Burnham


3 Answers

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

like image 148
HaNdTriX Avatar answered Nov 13 '22 00:11

HaNdTriX


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

like image 10
Trevor Burnham Avatar answered Nov 12 '22 22:11

Trevor Burnham


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}
like image 5
Tope Adekanbi Avatar answered Nov 13 '22 00:11

Tope Adekanbi