为包定义的模板设置数据上下文

Setting the data context for a template defined by a package

本文关键字:置数据 上下文 包定义 定义      更新时间:2023-09-26

下面是相关的代码模板代码:

<!-- display a list of users -->
<template name="available_user_list">
    <h2 class="cha_heading">Choose someone to chat with:</h2>
    <div class="row">
        {{#each users}}
            {{> available_user}}
        {{/each}}
    </div>
</template>
<!-- display an individual user -->
<template name="available_user">
    <div class="col-md-2">
        <div class="user_avatar">
            {{#if isMyUser _id}} 
            <div class="bg-success">
                {{> avatar user=this shape="circle"}}
                <div class="user_name">{{getUsername _id}} (YOU)</div>
            </div>
            {{else}}
            <a href="/chat/{{_id}}">
                {{> avatar user=this shape="circle"}}
                <div class="user_name">{{getUsername _id}}</div>
            </a>
            {{/if}}
        </div>
    </div>
</template>
<template name="chat_page">
    <h2>Type in the box below to send a message!</h2>
    <div class="row">
        <div class="col-md-12">
            <div class="well well-lg">
            {{#each messages}}
                {{> chat_message}}
            {{/each}}
            </div>  
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <form class="js-send-chat">
                <input class="input" type="text" name="chat" placeholder="type a message here...">
                <button class="btn btn-default">send</button>
            </form>
        </div>
    </div>
</template>
<!-- simple template that displays a message -->
<template name="chat_message">
    <div class="chat-message">
    {{> avatar user=user size="small" shape="circle"}} <div class="chat-center">{{user}}: {{text}}</div>
    </div>
</template>

和模板帮助程序:

Template.available_user_list.helpers({
  users:function(){
    return Meteor.users.find();
  }
})
Template.available_user.helpers({
  getUsername:function(userId){
    user = Meteor.users.findOne({_id:userId});
    return user.username;
  }, 
  isMyUser:function(userId){
    if (userId == Meteor.userId()){
      return true;
    }
    else {
      return false;
    }
  }
})

Template.chat_page.helpers({
  messages:function(){
    var chat = Chats.findOne({_id:Session.get("chatId")});
    return chat.messages;
  }, 
  other_user:function(){
    return ""
  }, 
})
Template.chat_message.helpers({
  user: Meteor.user()
})

我正在制作一个用户可以登录并相互聊天的网站。我已经下载了实用程序:头像包来显示用户的头像。头像图像基于用户用户名的第一个首字母。当我使用代码{{> avatar user=this shape="circle"}} available_user模板中呈现头像模板时,它会很好地显示头像中的首字母缩写,因为它与用户集合的上下文有关。

我还想在用户发送消息但模板chat_message位于聊天集合内数组的数据上下文中时显示头像。因此,它只显示默认头像,没有首字母。

包的文档没有完全指定如何为 useruserId 设置模板参数。有人可以帮忙解决这个问题吗?

我想通了。我将用户 id 包含在字段 userId 下的 messages 数组中的每个对象中,并在模板中将其设置为 {{> avatar userId=userId size="small" shape="circle"}}