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?
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.)
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}}
.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With