Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Language localization in Javacript



> ...Don't use indirect variable references. Let the data structure do the work:
> 
> strings = {
> 	english: { hi: "Hello world", bye: "Goodbye" },
> 	japanese: { hi: "こんにちは世界", bye: "さよなら" },
> 	french: { hi: "Bonjour tout le monde", bye: "Au revoir" },
> }
> 
> var language = "english";
> 
> document.writeln( strings[language]["hi"] );

I'm glad I read all the posts before replying; Simon's answer above is
what I was going to suggest. The ternary operator I used originally was
a shortcut, guessing you only needed English and Japanese.

However, I'd still have a global var:

T=strings[language];
...
document.writeln( T["hi"] );

Why? Because the output lines are going to be used in hundreds of
places, and typing strings[language] everywhere is tedious and
distracting (and also uses more CPU cycles - though no-one would notice).

Darren

P.S. You don't have to put all the strings in one huge object, as in the
above example. Going back to your original code:

var english = new Object ();
english.l00001 = "hello";
english.l00002 = "goodbye";
var japanese = new Object ()
japanese.l00001 = "今日は";
japanese.l00002 = "サヨナラ";

You then create the strings object (*) like this:

var strings={
	english:english,
	japanese:japanese,
	};

*: BTW, a Javascript object is the equivalent of PHP's associative array.


P.P.S. As others have said, this is all assuming you have a good reason
to have all languages statically embedded in an html page. Which it
sounds like you do.



-- 
Darren Cook, Software Researcher/Developer

http://dcook.org/work/ (About me and my work)
http://dcook.org/blogs.html (My blogs and articles)


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links