如何在使用Handlebars模板时指定如何在HTML中格式化值?

时间:2017-03-10 23:02:49

标签: javascript json handlebars.js

假设我有一个对象

var context = {
    subject: "Hello", 
    from: "Joe", 
    date:"2017-03-09T16:34:20Z", 
    message: "Test message", 
    msg_size: 1243, 
    tags: ['URGENT']
};

有没有办法定义每个对象类型应该如何在HTML模板中呈现 ?让我们说在一个地方我想要将日期格式化为“2017年3月9日”,另一个地方我希望日期说“1天前”(即使用Moment.js),或者我想要一个用固定的数字渲染的数字小数位数。

或者是通过首先将上下文值转换为字符串然后执行模板来应用值格式的唯一方法?指定如何在HTML本身格式化数据将会很方便。

2 个答案:

答案 0 :(得分:1)

我在这里为你创建了一个JSFiddle:https://jsfiddle.net/ohL5bjqb/

Goontracker关于使用助手是正确的。这是JS:

var context = {
  subject: "Hello",
  from: "Joe",
  date: "2017-03-09T16:34:20Z",
  message: "Test message",
  msg_size: 1243,
  tags: ['URGENT']
};

Handlebars.registerHelper('parsedDate', function(person) {
  return moment(context.date).format('MM/DD/YYYY')
});

Handlebars.registerHelper('daysAgo', function(person) {
  var now = moment(new Date()); //todays date
  var end = moment(context.date); // another date
  var duration = moment.duration(now.diff(end));
  var days = duration.asDays();
  return Math.round(days);
});

var source = $("#some-template").html();
var template = Handlebars.compile(source);
$('body').append(template(context));

HTML:

<script id="some-template" type="text/x-handlebars-template">
  <div>Subject: {{subject}}</div>
  <div>From: {{from}}</div>
  <div>Message: {{message}}</div>
  <div>Date: {{date}}</div>
  <div>Parsed Date: {{parsedDate}}</div>
  <div>Days Ago: {{daysAgo}}</div>
</script>

输出:

Subject: Hello
From: Joe
Message: Test message
Date: 2017-03-09T16:34:20Z
Parsed Date: 03/09/2017
Days Ago: 1

答案 1 :(得分:0)

没有办法将格式化程序放在模板本身中, 你要找的是Handlebars.registerHelper 即在呈现模板之前

handlebars.RegisterHelper("fooIze", function(){
  return "foo";
});

然后在你的模板中 {fooIze&#34; ANYTHING&#34;} 将呈现为

foo
像这样 http://jaskokoyn.com/2013/08/08/custom-helpers-handlebars-js-tutorial/