json mustache.js日期格式

yiytaume  于 2022-11-26  发布在  其他
关注(0)|答案(7)|浏览(124)

我已经开始使用mustache.js了,到目前为止我印象非常深刻。虽然有两件事让我困惑。第一件事导致了第二件事,所以请耐心等待。

我的JSON

{"goalsCollection": [
    {
        "Id": "d5dce10e-513c-449d-8e34-8fe771fa464a",
        "Description": "Multum",
        "TargetAmount": 2935.9,
        "TargetDate": "/Date(1558998000000)/"
    },
    {
        "Id": "eac65501-21f5-f831-fb07-dcfead50d1d9",
        "Description": "quad nomen",
        "TargetAmount": 6976.12,
        "TargetDate": "/Date(1606953600000)/"
    }
]};

我的处理功能

function renderInvestmentGoals(collection) {
    var tpl = '{{#goalsCollection}}<tr><td>{{Description}}</td><td>{{TargetAmount}}</td><td>{{TargetDate}}</td></tr>{{/goalsCollection}}';
    $('#tblGoals tbody').html('').html(Mustache.to_html(tpl, collection));
}

Q1如您所见,我的'TargetDate'需要解析,但我不确定如何在当前函数中进行解析。
问题2假设我想在渲染之前对一个或多个对象执行某些功能或格式化,最好的方法是什么?

4ioopgfo

4ioopgfo1#

您可以使用mustache(5)中的“Lambdas”

"TargetDate": "/Date(1606953600000)/",
"FormatDate": function() {
    return function(rawDate) {
        return rawDate.toString();
    }
}, ...

然后在标记中:

<td>
{{#FormatDate}}
    {{TargetDate}}
{{/FormatDate}}
</td>

从链接:
当值是可调用对象时,如函数或lambda,对象将被调用并传递文本块。传递的文本是文本块,未呈现。

anhgbhbe

anhgbhbe2#

我为Mustache.js创建了一个小的扩展,它支持在表达式中使用格式化程序,如{{expression|格式化程序}}
无论如何,您都需要创建一个函数来解析日期值,如下所示:

Mustache.Formatters = {
        date: function( str) {
          var dt = new Date( parseInt( str.substr(6, str.length-8), 10));
          return (dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear());
        }
      };

然后将格式化程序添加到表达式中:

{{TargetDate | date}}

您可以从此处获取代码:http://jvitela.github.io/mustache-wax/

ss2ws0br

ss2ws0br3#

这是很久以前的事了,但在这上面找得到了完全一样的东西。Mustachejs(现在)允许你调用传递数据的函数,而且不仅如此;在该函数中,this的值是在一段中为真的任何值。
如果我的模板是这样的:

{{#names}}
    <p>Name is:{{name}}</p>
    <!-- Comment will be removed by compileTemplates.sh
         #lastLogin is an if statement if lastLogin it'll do this 
         ^lastLogin will execute if there is not lastLogin      
    -->
    {{#lastLogin}}
    <!-- 
      formatLogin is a method to format last Login 
      the function has to be part of the data sent 
      to the template
    -->
    <p>Last Login:{{formatLogin}}</p>
    {{/lastLogin}}
    {{^lastLogin}}
    not logged in yet
    {{/lastLogin}}
    {{#name}}
     passing name to it now:{{formatLogin}}
    {{/name}}
{{/names}}

还有这样的数据:

var data={
    names:[
        {name:"Willy",lastLogin:new Date()}
    ],
    formatLogin:function(){
          //this is the lastDate used or name based on the block
                  //{{#name}}{{formatLogin}}{{/name}}:this is name
                  //{{#lastLogin}}{{formatLogin}}{{/lastLogin}}:this is lastLogin
          if(!/Date\]$/.test(Object.prototype.toString.call(this))){
              return "Invalid Date:"+this;
          }
          return this.getFullYear()
            +"-"+this.getMonth()+1
            +"-"+this.getDate();
    }
};
var output = Mustache.render(templates.test, data);
console.log(output);
ozxc1zmp

ozxc1zmp4#

您可以使用简单的String方法来取得时间戳记:

goalsCollection.targetDate = goalsCollection.targetDate.substring(6,18);

当然,这取决于你的时间戳每次都是相同的长度。另一个选择是:

goalsCollection.targetDate = 
  goalsCollection.targetDate.substring(6, goalsCollection.targetDate.length - 1);

这些技术并不是特定于Mustache的,可以用于处理任何库的数据。有关详细信息,请参阅Mozilla Developer Center Documentation on substring

uurity8g

uurity8g5#

要在json中声明一个函数,您可以随时这样做。

var json = '{"RESULTS": true, "count": 1, "targetdate" : "/Date(1606953600000)/"}'

var obj = JSON.parse(json);
obj.newFunc = function (x) {
  return x;
}

//OUTPUT
alert(obj.newFunc(123));
mw3dktmi

mw3dktmi6#

用于分析ISO-8601日期并将其格式设置为UTC的“lambda”函数的工作示例:
第一个
如果您想要更华丽的日期格式,您可以使用例如:

new Date().toLocaleDateString('en-GB', {
    day : 'numeric',
    month : 'short',
    year : 'numeric', hour: 'numeric', minute: 'numeric'
})
// outputs '14 Apr 2022, 11:11'
kzmpq1sx

kzmpq1sx7#

我也在我的项目中使用了Mustache,因为它可以在客户机/服务器之间共享。我最终做的是在服务器端将所有值(日期、货币)格式化为字符串,这样我就不必依赖辅助Javascript函数了。不过,如果你在客户机端对这些值进行逻辑运算,这可能对你来说效果不太好。
您可能还想考虑使用handlebars.js,它本质上是Mustache,但具有可能有助于客户端格式化(以及更多)的扩展。这里的损失是您可能无法找到handlebar的服务器端实现,如果这对您很重要的话。

相关问题