nebenmir
nebenmir

Reputation: 891

How to localize javascript files in wicket

Hallo, a Wicket i18n question: I have a javaScript file, that holds strings I want to localize. Ideally I want to localize the whole file. Something like

where wicket automatically chooses the right js file, as it does with property files.

Any one knows how to do that?

Upvotes: 5

Views: 854

Answers (2)

Moroianu Alexandru
Moroianu Alexandru

Reputation: 167

The actual solution works if the Strings are already in the Javascript files.But what happens when you have localized Strings in your database and want to pass them to your Javascript code? You could create a XML file named YourPageJS.xml and store Javascript code there identified by some keys.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>

    <entry key="showModal">
    <![CDATA[ 

        $(''#{0}'').modal(''show'',{1});

    ]]>
    </entry>
</properties>

You call this code through the following method that is located in an utility class,passing your parameters:

    public static String getJsByClass(Class clazz, String name, Object... params)
    {
        ResourceBundle resources = ResourceBundle.getBundle(clazz.getName()
                + "JS", Locale.getDefault(),
                new XMLResourceBundleControl());

        String mesaj = resources.getString(name);
        mesaj = MessageFormat.format(mesaj, params);

        return mesaj;
    }

The call looks like this :

YourUtils.getJsByClass(YourPage.class, "showModal" ,"firstParameter","secondParameter");

where the parameters could be your localized strings.In the above case,the first parameter is the markup Id.You can add it to your html head like this:

response.render(JavaScriptHeaderItem.forScript(YourUtils.getJsByClass(YourPage.class, "showModal" ,"firstParameter","secondParameter"), "yourJSid")); (Wicket 6)

Also,in the XML you must transform two characters: 'becomes '' and { becomes '{' for parsing reasons.

Upvotes: 0

igor.vaynberg
igor.vaynberg

Reputation: 1453

Pass the locale to the resource reference:

class MyPage extends WebPage implements IHeaderContributor {
    public void renderHead(IHeaderResponse response) {
        response.renderJavascriptReference(new ResourceReference(
        MyPage.class, "my.js", getLocale(), getStyle()));
    }
}

Upvotes: 8

Related Questions