I have a collection that stores phone numbers for companies. If a company has a phone number, draw those phone numbers. If a company has no phone number, don't draw any.
Currently it half works. It will not draw the phone numbers if no numbers are in the collection, but it still draws the < h4 >Phone< /h4 > heading and I don't want it to.
Here's the code:
<template name="orgPage">
<h2>Organisation Name: {{name}}</h2>
<h3>Contact Details</h3>
<ul>
{{#if phone}}
<h4>Phone</h4>
{{#each phone}}
<li>{{number}} ({{type}})</li>
{{/each}}
{{else}}
<p>No contact numbers</p>
{{/if}}
</ul>
</template>
and
Template.orgPage.helpers({
'phone': function() {
return organisationsPhoneNumbers.find({ orgId: currentOrgId })
}
});
How can I get it to NOT draw the < h4 >Phone< /h4 > if there is no data returned from the collection?
short answer
Keep all of your original code and replace {{#if phone}}
with {{#if phone.count}}
long answer
Spacebars has a really cool path evaluation feature, which is best explained with an example.
Imagine you have a post
document in your current context. Each post
is modeled to have a fetchAuthor
helper, which returns a user document. Let's suppose you need the lower cased version of the author's last name. In JavaScript you could write something like:
post.fetchAuthor().profile.firstName.toLowerCase()
Now if we need that value in a template we can write:
{{post.fetchAuthor.profile.firstName.toLowerCase}}
As spacebars evaluates each identifier in the path, it checks to see if it's a function - if it is, it invokes it. Note this only works if the called functions take no arguments.
Circling back to our original example, the phone
helper returns a cursor, which has a count
function. We can write {{#if phone.count}}
and spacebars will figure out that we mean phone.count()
because count
is a function.