How to localize javascript files in wicket
Asked Answered
T

2

5

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

  • my.js
  • my_de.js
  • my_fr.js
  • ...

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

Any one knows how to do that?

Tacitus answered 20/10, 2010 at 8:8 Comment(0)
P
8

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()));
    }
}
Prevaricator answered 20/10, 2010 at 21:3 Comment(1)
I came up with a solution that used PackageResource, but yours is even shorter. Thanks a lot.Tacitus
F
0

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.

Finnish answered 12/4, 2017 at 15:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.