简体   繁体   English

如何创建流星模板助手来检查平等性?

[英]How Do I Create Meteor Template Helper to Check Equality?

I am making a chat web app. 我正在制作一个聊天网络应用程序。 people can login with facebook and talk (insert message into mongoDB). 人们可以使用Facebook登录并交谈(将消息插入mongoDB)。

showing the text is simple: javascript: 显示文字很简单:javascript:

  messages: function () {
    return Messages.find({}, {sort: {createdAt: 1}});
  } 

each message has these attributes: 每条消息具有以下属性:

text: text,
      createdAt: new Date(),            // current time
      owner: Meteor.userId(),           // _id of logged in user
      username: Meteor.user().profile.name

It works fine, but I want to "style the message differently" depending on whether the message's owner is equal to currentUser (ie whether it's my message or others message) 它工作正常,但是我想根据消息的所有者是否等于currentUser(即,是我的消息还是其他消息)来“对消息进行样式不同”

For example, I want my message to be float:right and others message to be float:left 例如,我希望我的消息是float:right,而其他消息是float:left

I am thinking the code probably looks something like this: 我认为代码可能看起来像这样:

  {{#if mymsg}}
    <div class="msgdiv_my">
       <span class="message">{{text}}</span>
    </div>
  {{else}}
    <div class="msgdiv">
      <span class="message">{{text}}</span>
    </div>
  {{/if}}

Where and how to write the mymsg function (which should return True if the message.owner == currentUser , and false otherwise) 在哪里以及如何编写mymsg函数(如果message.owner == currentUser ,则应返回True,否则应返回false)

You would usually write those checks in a template helper, like this: 通常,您将在模板帮助程序中编写这些检查,如下所示:

Template.myTemplate.helpers({
  ownDocument: function (doc) {
    return doc.owner === Meteor.userId();
  }
});

Then in myTemplate , call your helper like this: 然后在myTemplate ,像这样调用您的助手:

<template name="myTemplate">
  {{#if ownDocument text}}
    <div class="msgdiv_my">
       <span class="message">{{text}}</span>
    </div>
  {{else}}
    <div class="msgdiv">
      <span class="message">{{text}}</span>
    </div>
  {{/if}}
</template>

Although you may want to implement a global "equals" helper to your meteor app's client, as it sadly is not built in Meteor Spacebars yet: 尽管您可能想为流星应用程序的客户端实现一个全局的“等于”助手,但遗憾的是它尚未内置在Meteor Spacebars中:

Template.registerHelper('equals',
    function(v1, v2) {
        return (v1 === v2);
    }
);

This way, you would call: 这样,您将调用:

{{#if equals text.owner currentUser._id}}

And get the same result. 并得到相同的结果。

KyleMit wrote a lengthy answer for all your equality check needs in Meteor. KyleMit为您在Meteor中的所有平等检查需求写了一个冗长的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM