Search code examples
javascriptmeteorspacebarsmeteor-helper

How Do I Display Placeholder Text When No Documents Match User in Meteor?


I have a script that runs through a collection of photo documents, checks if they match the current user ID, and then renders the template.

<ul id="settings-photos">
    {{#each photos}}
        {{#if person}}
            {{> photo}}
        {{/if}}
    {{/each}}
</ul>

If no photos exist for a user, I would like to display a "Click to upload a photo!" message. How would I write a condition for this in the Spacebars/Meteor way?

My personhelper code is as follows

person : function () {
    user = Meteor.userId();
    photoUser = this.user;
    console.log(this);
    if(user == photoUser) {
        return true;
    }
}

EDIT: I have accepted the answer that led me to the solution. My final script was

photos : function () {
    var id = Meteor.userId();
    var photos = Photos.find({user: id}).fetch();

    return photos;
}

and then in HTML

<ul id="settings-photos">
    {{#each photos}}
        {{> photo}}
    {{/each}}
    {{#unless photos}}
        Click to upload an image
    {{/unless}}
</ul>

Solution

  • While doing a loop through photo collection and checking for user will work, a better way of doing it would be to write a UI/Template helper which extracts the photo of user. That way, if you end up changing the schema of user, or photo collection, you only need to change the helper.

    Template.registerHelper(userPhoto, function(userId){
        var userPhoto = Photos.findOne({person: userId});
        if(userPhoto && userPhoto.photoUrl) {
            return userPhoto.photoUrl;
        }
    })
    

    This way you can write your template much more cleanly. As in,

    <ul id="settings-photos">
        {{#if userPhoto currentUser._id}}
            {{> userPhoto currentUser._id}}
        {{else}}
            <a href="#">No Photos found. Click here to upload</a>
        {{/if}}
    </ul>
    

    Original Answer:


    <ul id="settings-photos">
        {{#each photos}}
            {{#if person}}
                {{> photo}}
            {{/if}}
        {{/each}}
        {{#unless photos}}
            <a href="#">No Photos found. Click here to upload</a>
        {{/unless}}
    </ul>