Fid
Fid

Reputation: 506

How do I translate text in .java source files?

I have an enum like this

public enum CheckboxFeature {

    Option1(" choose this"),
    Option2(" or this"),
    Option3(" maybe this"),
    Option4(" lastly this");

    @Getter
    private final String text;

    public static CheckboxFeature fromName(String v) {
        for (CheckboxFeature c: CheckboxFeature.values()) {
            if (c.name().equalsIgnoreCase(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }
}

This shows the four options as checkboxes in the web view

<form:checkboxes items="${features}" path="enabledFeatures" itemLabel="text" delimiter="<br/>"/>

How can I translate these options? I use fmt:message for the rest of the translations in the web view.

I have tried

Option1(" <fmt:message key=\"text.test\"/>"),

and

Option1(" ${option1}"),

with

<fmt:message key="text.select" var="option1"/>

in the .jsp. Neither of them work, so it seems it can't work this way. What is the correct way of translating the strings? Ideally using the fmt:message and i18n resources (lang.properties files) that are in place and working on the rest of the servlet?

Upvotes: 6

Views: 845

Answers (2)

DavidW
DavidW

Reputation: 1421

Optimally, you get the resource key from the enum, and look that up.

public enum CheckboxFeature {
    Option1("label.option1.key"),
    Option2("label.option2.key"),
    Option1("label.option3.key"),
    Option2("label.option4.key");

    private final String key;
    [...]

I don't know how to nest a l10n lookup in the itemLabel attribute, so I would write something like:

<c:forEach items="Options.values()" var="current">
    <form:checkbox path="selectedOptions" value="${current.name()}"/> <fmt:message key="${current.getKey()}"/>
</c:forEach>

Upvotes: 6

eve
eve

Reputation: 1

1、CheckboxFeature add method like:

 public static List<String> getAllCheckboxFeature(String v) {
        return Arrays.asList(Option1.getText(),...Option4.getText());
 }


2、than use the jstl like:

<c:forEach items="${options}" var="option">
    <input type="checkbox" ="${option}">
</c:forEach>

Upvotes: 0

Related Questions