Translating JavaScript files

Translating JavaScript files

The translation of JavaScript Files is more or less similar to that of PHP code, and is handled by the sapphire/javascript/i18n.js file. This script will try to detect the current locale based on the http-equiv="Content-language" metatag on loading. If no locale can be established, the script will default to its defaultLocale property. (I'm not quite sure if this is still the case for version 2.4.5, need to check).

The _t( ... ) function

First you need to internationalize your javascript file in the following manner:

// mystring = 'this is a message';

mystring = ss.i18n._t('MYSCRIPT.MESSAGE', 'this is a message');

The Language file

Next you need a language file. Start with the default en_US.js file in your modules javascript/lang/ directory.


if(typeof(ss) == 'undefined' || typeof(ss.i18n) == 'undefined') {
	if(typeof(console) != 'undefined') console.error('Class ss.i18n not defined');
} else {
	ss.i18n.addDictionary('en_US', {
		'MYSCRIPT.MESSAGE': 'this is a message',
		'MYSCRIPT.SOMETHING': 'Something completely different'

After that translate this file into any language you want. Aside from adding the correct filename and translating strings, don't forget to set the correct locale for the dictionary as well :-)

Loading the language file

Finally you need to point SilverStripe to the language files, by adding a requirement to the php code. In a page this would be in init() for the website or maybe in getCMSFields() for the backend. The following will add all files in the javascript/lang directory (but you can be selective as well):


Note: Sometimes, especially in the cms, the locale for the current userprofile is not detected correctly or just not in time. In case of emergency, you could hardcode the defaultlocale property in i18n.js to the preferred locale.


Het versturen van reacties is uitgeschakeld.

RSS feed voor reacties op deze pagina