Search code examples
javascriptcssmeteorspacebars

Meteor conditional CSS


How can I set the background-color: #ccc to the {{colorLike}} helper? This colour is used for the list items.

<template name="viewPost">
Names:
{{#each userNames}}
<li class="name"><a class="{{colourLike}}" href="{pathFor 'viewItem'}" >{{name}}</a></li>
{{/each}}
</template>

I would also like to register another helper {{colorDislike}} in bacground-colour: #fff. This is so that that if an element exists in a particular field, {{colourDislike}} will over-ride {{colorLike}}. I'm gathering I can achieve this with an 'if' statement.

Template.viewPost.helpers({
    userNames: function(){
        var selectedPostId = Session.get('postId');
        var arrayOfLike = Posts.find({_id: selectedPostId}, {fields: {likes: 1}}).fetch();
        var sumArray = _.chain(arrayOfLike).pluck('likes').flatten().value();
            return Meteor.users.find({_id: {$in: sumArray}});
},
});

The selected post is from the session set from another template created upon clicking the post title. When clicked, the user can see a list of all the userNames of those that liked the post. So I'm aiming to get these names <li class="name"><a class="{{colourLike}}" href="{pathFor 'viewItem'}" >{{name}}</a></li> to be in a certain colour.

When the user clicks the name, they are able to view the 'item' which is a field in this particular user profile on the viewItem template. This template also displayed a button to 'dislike' the item. If so, the userId of the item is stored in the 'dislike' field of the Post document.

<template name="viewItem">
 {{profile.item}}
  <div class="dislike">
    <button type="button" class="btn btn-default btn-lg">
     <span class="glyphicon glyphicon-remove"></span> Dislike
    </button>
 </div>
</template>

Solution

  • The most idiomatic way to do this is to apply a semantic class - e.g. "liked" or "disliked" - then in the CSS, apply the background colour to elements with that class.

    {{#each likingUsers}}
      <li class="name"><a class="liked" href="{{pathFor 'viewItem'}}" >{{name}}</a></li>
    {{/each}}
    {{#each dislikingUsers}}
      <li class="name"><a class="disliked" href="{{pathFor 'viewItem'}}" >{{name}}</a></li>
    {{/each}}
    

    Here likingUsers is the same userNames helper you already wrote, and dislikingUsers is similar, but it gets the users who disliked it instead.

    /* css */
    
    a.liked {
      background-color: #ccc;
    }
    
    a.disliked {
      background-color: #fff;
    }
    

    This way, if you later decide to style liked/disliked posts differently - e.g. make liked posts green, or put a strikethrough on the disliked posts - you only have to change CSS, not JS code or HTML templates.