【问题标题】:How to alter the display of what Spacebars outputs?如何更改空格键输出的显示?
【发布时间】:2015-04-03 11:52:37
【问题描述】:

所以我在模板中有这样的东西:

{{#each posts}}
    <li>{{date}}</li>
{{/each}}

这显示得很好,但问题是我的“日期”变量显示为Sat Feb 07 2015 19:47:13 GMT-0800 (PST),这是准确的,但有点冗长且不必要。

我希望日期看起来更简单,例如 February 7, 2015。但是,请原谅我缺乏理解,但我知道如何做到这一点的唯一方法是以漂亮的格式存储它,但如果我必须这样做,这似乎并不有效每次我想要一些不同的东西。

理想情况下,我想将其包装在 moment() 中并生成如下内容:

moment(date).format("MMMM Do YYYY")

我试着把它换成这个,但它不起作用:

{{#each posts}}
    <li>{{moment(date).format("MMMM Do YYYY")}}</li>
{{/each}}

【问题讨论】:

    标签: meteor spacebars


    【解决方案1】:

    试试这个。

    Template.example.rendered = function(){
    //here we are getting a new date
    var d = moment(new Date());
    //here we take the li element and we set it on the html
    document.getElementById("dateFormated").innerHTML = d.format('LL');
    }
    
    
    <template name="example">
    <li id="dateFormated"> </li>
    </template>
    

    更新

    由于您使用的是 {{#each}} 迭代器

    你可以这样做。

    var d = moment(new Date()).format('LL');
    

    var d = moment(new Date());
    dFormat = d.format('LL');
    

    在插入时,插入像Posts.insert({submitted:dFormat})这样的字段

    像你一样在{{each}}打电话

    {{#each posts}}
        <li>{{subbmited}}</li>
    {{/each}}
    

    不插入数据库(另一个选项)

    Template.example.helpers({
      formattedData:function(){
       return moment(new Date()).format('LL');
      } 
    })
    
    {{#each posts}}
            <li>{{formattedData}}</li>
        {{/each}}
    

    【讨论】:

    • 我正在尝试通过从空格键输出的数据来执行此操作。除非您建议我在呈现模板后使用 jQuery 操作 DOM,然后读取/替换每个单行项目?
    • 我认为一般情况下您不应该将格式化的日期插入数据库。
    【解决方案2】:

    添加助手

    Template.yourTemplate.helpers({
      formattedDate: function(){
        return moment(this.date).format("MM/DD/YYYY");  // or whatever format you prefer
      }
    });
    

    【讨论】:

    • 啊,就是这个。我不知道您可以在帮助程序中使用“this”来引用从另一个帮助程序返回的项目集合。如果有人对此感到困惑,我认为“this.date”不会引用“帖子”中的每个,而是最初传递给模板的“日期”变量。
    • 它指的是你当前的数据上下文,所以由于你当前的数据上下文是它被调用时的帖子,你可以调用'this.date'来访问它。
    【解决方案3】:

    您可以创建一个注册助手来处理日期格式:

    helper.js

    Template.registerHelper('FormatDate', function(date){
        return moment(date).format("MMMM Do YYYY")
    })
    

    现在你可以这样做了:

    {{#each posts}}
        <li>{{FormateDate date}}</li>
    {{/each}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-21
      • 2017-05-15
      • 1970-01-01
      • 2016-10-08
      • 2019-08-19
      • 2019-01-29
      • 2019-02-04
      • 1970-01-01
      相关资源
      最近更新 更多