Hamid
Hamid

Reputation: 478

Freemarker template currency symbol encoding issue

Using freemarker template with java is producing an incorrect currency symbol. Expecting $ however getting ¤

I've tried setting the encoding and outputEncoding on the freemarkerConfig with no luck

    public String processTemplate(String freemarkerTemplate, Object model, Locale locale) throws IOException, TemplateException {
        try {
            this.freemarkerConfig.setSetting("locale", locale.getLanguage());
            this.freemarkerConfig.setSetting("time_zone", "EST");
        } catch (TemplateException e) {
            log.warn("Failed to set locale {} for freemarker template.", locale.getLanguage(), e);
        }
        //freemarkerConfig.setEncoding(locale, "UTF-8");
        //freemarkerConfig.setOutputEncoding("UTF-8");
        Template template = freemarkerConfig.getTemplate(freemarkerTemplate);
        //template.setOutputEncoding("UTF-8");
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
    }

Also have tried adding the <#ftl encoding="utf-8"> to my template file without any difference.

EDIT

This is how I'm using the currency function: ${amountValue?string.currency}

Upvotes: 0

Views: 1141

Answers (1)

ddekany
ddekany

Reputation: 31132

This is not an encoding issue. The ¤ character is called the currency sign, and Java number format prints it if it doesn't know the actual currency. The reason it doesn't know it is that you set the FreeMarker locale setting to locale.getLanguage() (like "en"), instead of locale.toString() (like "en_US", which also contains a country), and the language is not enough to decide the currency, it's the country that decides that.

Also, if you can, avoid setSetting, and call the strongly typed methods, like freemarkerConfig.setLocale(locale), freemarkerConfig.setTimeZone(timeZone), etc.

Upvotes: 3

Related Questions