Search code examples
javascriptmeteormeteor-blazemeteor-accounts

Checking equality in Blaze?


The user can only delete a post if he was the one who posted it.However a user can see all the posts.The javascript code is:

var postedBy = Meteor.user();
var currentPost = this._id;
Posts.insert({
name:postName,
createdAt:new Date(),
postId:currentPost,
postedBy:postedBy
});

The HTML code is:

<template name="posts">
{{#if currentUser}}
{{> addPost}}
<ul>
    {{#each post}}
        <li>{{> postItem}}</li>

    {{/each}}
</ul>
{{/if}}
</template>


<template name="postItem">
    <li>
    <h4>{{name}}</h4>
    <i>Posted by {{postedBy.username}} on {{createdAt}}</i>

     [<a href="#" class="delete-post">Delete</a>] 

    </li>
</template>
<template name='addPost'>
<input type='text' placeholder='Add post here' name='postName' id ='myinput'>
<button class="btn btn" type="button" id='btn'>Post</button>
</template>

Both currentUser.username and postedBy.username are displaying the names of the logged in user and the user who posted a particular post respectively.

I am trying to work with the Delete anchor tag.

{{#if currentUser.username==postedBy.username}} 
[<a href="#" class="delete-post">Delete</a>]
{{/if}}

But it shows error in command prompt.I know it is wrong but I can't think of any other way.How do i write this 'if' statement to check if the current user was the one who posted this post? Please help as I am new to Meteor.Sorry for bad English.


Solution

  • You can't use arbitrary JavaScript expressions in spacebars. Add a helper like this:

    Template.postItem.helpers({
      canDelete: function (){
        return Meteor.user().username === this.postedBy.username;
      }
    });
    

    Which you can then use in your template like this:

    {{#if canDelete}}
      <a href="#" class="delete-post">Delete</a>
    {{/if}}
    

    Also note, instead of copying the user object into each post, the recommended way is to store the user's id in postedBy.