【问题标题】:how to format result of Collection.find before passing to template如何在传递给模板之前格式化 Collection.find 的结果
【发布时间】:2014-04-20 16:12:51
【问题描述】:

HTML:

    <div class="leaderboard">
        {{#each players}}
          {{> player}}
        {{/each}}
    </div>
    <template name="player">
      <div class="player {{selected}}">
        <span class="name">{{name}}</span>
        <span class="score">{{score}}</span>
        <span class="joindate">{{joindate}}</span>
      </div>
    </template>

JS:

Players = new Meteor.Collection("players");
if (Meteor.isClient) {
  Template.players = function () {
    return Players.find();
  };
}
if (Meteor.isServer) {
  Meteor.startup(function () {
    if (Players.find().count() === 0) {
      var names = ["Ada Lovelace",
                   "Grace Hopper",
                   "Marie Curie",
                   "Carl Friedrich Gauss",
                   "Nikola Tesla",
                   "Claude Shannon"];
      for (var i = 0; i < names.length; i++)
        Players.insert({name: names[i], 
                       score: Math.floor(Random.fraction()*10)*5,
                       joindate: new Date().getTime()
                     });
    }
  });
}

在上面的示例中,我将 joindate 存储为 unix 时间戳。如何在返回 Template.players 函数之前将加入日期变量格式化为 Collection.find 结果中的可读日期。

我知道我可以在插入命令中格式化日期,但我的问题是在传递给模板之前如何操作/格式化 collection.find 中的数据。

【问题讨论】:

    标签: mongodb meteor handlebars.js


    【解决方案1】:

    您可以在创建Collection 时传递transform function

    var Players = new Meteor.collection('players', { 
        transform: function(doc) { 
            doc.joindateStr = (new Date().getTime()).toString(); 
            return doc;
        }
    });
    

    然后在您的模板中使用joindateStr。或者您可以将joindate 本身覆盖为Date 对象。

    transform 函数将应用于findfindOne 返回的所有文档。它也可以在第二个参数处显式传递给find 或 findOne`。

    【讨论】:

    • 非常感谢!一件很难的事,你缺少退货文件;在函数中。
    • @ian 包含它。谢谢!
    猜你喜欢
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多