[英]In Freemarker, how do I use a custom NumberFormat or DateFormat for 1 line (but not the rest of the report)?
I have 2 numbers I want to display in a freemarker file: 我想在freemarker文件中显示2个数字:
Benchmark long id
基准long id
Benchmark long timeSpend
基准long timeSpend
The id should use the default NumberFormat
instance, but the timeSpend should use my MillisecondsSpendNumberFormat
instance, so I get something like this in the output: id应该使用默认的NumberFormat
实例,但timeSpend应该使用我的MillisecondsSpendNumberFormat
实例,所以我在输出中得到这样的东西:
id: 1 234 567
id: 1 234 567
timeSpend: 1min 23sec 456ms
timeSpend: 1min 23sec 456ms
How do I use my NumberFormat
instance for 1 long
instance, but not for all of them? 我如何使用我的NumberFormat
实例为1 long
实例,但不是所有实例?
You could give your formatter instance to the Freemarker template (add it to the model that contains the objects being passed to the template) and then explicitly call its format() method to format the number. 您可以将您的格式化程序实例提供给Freemarker模板(将其添加到包含传递给模板的对象的模型),然后显式调用其format()方法来格式化该数字。
Something like 就像是
timeSpend: ${myCustomFormatter.format(timeSpend)}
You can use ${someNumber?string("somePattern")}
to use non-default format for a single occasion. 您可以使用${someNumber?string("somePattern")}
来为单个场合使用非默认格式。 But your real problem will be that FreeMarker always uses DecimalFormat
for number formatting, and you can only specify the pattern. 但是你真正的问题是FreeMarker总是使用DecimalFormat
进行数字格式化,你只能指定模式。 So you can't use MillisecondsSpendNumberFormat
at all, unless you invoke it manually. 所以你根本不能使用MillisecondsSpendNumberFormat
,除非你手动调用它。 You can either do that by putting a MillisecondsSpendNumberFormat
instance into the data-model and call it's Java API from the template, or by implementing a TemplateMethodModelEx
that does the formatting internally, then pull it into some commonly #include
-d/ #import
-d file with <#assign formatTimeSpent = "com.example.MyTimeSpentFormatter"?new()>
and then use ${formatTimeSpent(someNumber)}
in the templates. 您可以通过将MillisecondsSpendNumberFormat
实例放入数据模型并从模板中调用它的Java API,或者通过实现在内部执行格式化的TemplateMethodModelEx
,然后将其拉入一些常见的#include
-d / #import
-d来实现。文件与<#assign formatTimeSpent = "com.example.MyTimeSpentFormatter"?new()>
然后在模板中使用${formatTimeSpent(someNumber)}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.