FreeMarker is a cool Java template engine, for almost every purpose, especially for the web.
I have adapted FreeMarker for quite some months, and been very happy with it since. However, there's one thing in FreeMarker that make me feel *damn* uncomfortable. It's the number format. FreeMarker will *smartly* add "comma" to make my number more readable. So, 1000 should be rendered as "1,000".
Back to the past, I adapt FreeMarker as an supplement into my existing code based on Spring MVC. So, I search around for solution. Some guys on the internet suggest I added a class name FreeMarkerConfigurer to my Spring beans definition and add a property named "number_format" with value of "0.####" and the problem should go away.
However, I tried without any success. I guess I make some typos so I tried again and again. A lot of article, and my problem remained unsolved. Finally, after hours of frustration, I switched to the the hard way: Add "?c" after every number I'm about to print into the screen (it's an instruction that tell FreeMarker engine to not add the comma into the number).
Well, thing went well at first. But I'm not a man of good memory. So, after few months of development, I have introduced few dozens of "?c" but forget to add this instruction for hundreds of numbers, most of them lied in the link.
So, what is the problem? Glad you asked.
Given I want to give user an access to a database record. So I give him the link:
Link
The link work well, if record.id<1000. If the record is a number that exceeds 1000, for example, 1002, then I get this link:
/database/rec/1,002
You can notice a *comma* was added to the number, and thus make the link incorrect.
I have hundreds of these kind of links in my templates. So, I'm hanging my self on a sting of the sword, waiting for my app to gradually fail....
Well, I shouldn't let it happen, right?
So, this time, I did an exploration through these FreeMarker configuration. Thanks to maven dependency management and eclipse awesome exploration tool, I finally notice a protected method name createConfiguration which FreemarkerServlet used to instantiate configuration itself. The method was declared as protected for some reason, and that reason allow me to subclass it and feed the FreemarkerServlet my desired configuration.
You guess, here is the code:
import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
public class CustomizedFreemarkerServlet extends FreemarkerServlet {
/**
*
*/
private static final long serialVersionUID = 3079263156037673099L;
@Override
protected Configuration createConfiguration() {
Configuration conf = super.createConfiguration();
conf.setNumberFormat("0.#####");
return conf;
}
}
Just a few lines, and now things are in order. I'm back into a safe living condition.
Thứ Hai, 17 tháng 5, 2010
Đăng ký:
Bài đăng (Atom)