Multi language support - javascript

I'm developing a HTML5 application that uses jQuery. I want to make it multi language: detecting user language and changing all literals to user's language.
I think that one approach is to use one HTML file for each language supported, but it is a waste of space.
Another approach could be use jQuery to change all literals to user's language. But I'm not sure how to do this.
What do you think? Is there a better approach?
UPDATE:
I've forget it to say that I have some literals inside JavaScript too.

Coulnd't you do some sort of server-side query to the user's language and then load the appropriate text automatically? Maybe even a CMS is appropriate here.
For all the Javascript code, I would use String literals as a variable. So you can load a different language file appropriate to the user language.
File english.js:
var messages_siteA1 = "This is an alert.";
var messages_siteA2 = "...";
// ...
File german.js:
var messages_siteA1 = "Dies ist eine Warnung.";
var messages_siteA2 = "...";
// ...
And in your Javascript:
alert(messages_siteA1);
Or am I missing the point here? ;)

In the HTML5 Demo of my, the "HTML5 Word Clouds",
http://timc.idv.tw/wordcloud/
(source code can be found at https://github.com/timdream/wordcloud)
I wrote separate HTML for different languages, and includes a single set of Javascript files. For literal strings with in the script, I collect them into an object (named T) and put it into <script> block of each HTML files.
This give me the flexibility to customize pages for each language; as you can see, I listed CNN as example in English version, but list other sources in the Chinese version.

If you absolutely have to do it at client-side, how about using a json or xml file to store your translations? This avoids the trouble of creating copies of the same page. For example, in your json. you'd have "welcome_eng": "welcome" and "welcome_fr": "bienvenue", etc.
Then you load the appropriate one using javascript, as in, get the variables like this:
blablabla=["welcome_"+language]
Or, if you want even less work, your welcome text's div will have the id "welcome", then your javascript gets the id and add the appropriate content.

It mostly depends on how dynamic or static your pages are: If they contain much text, than it will be easier to duplicate the page for each language. In this case it is very important to carefully isolate HTML from CSS and scripts. All CSS and scripts should be stored in separate pages, in order to avoid having to update all translations whnever you update a style or a script.
OTOH, if it is mostly dynamic, than it makes sense to replace text snippets by their translation when creating the page. But I wouldn't do the text replacement client-side (jQuery). It's a server-side job.
Edit: If you have javascript literals, you should then of course keep them side by side with the HTML, either in the HTML file or in a separate .js file. But it remains up to the server to deliver the contents in the correct language.

Related

Create a multilingual website

I am an experienced Android developer and in my apps I am used to providing multiple string.xml resource files for different languages.
Is there any similar approach to achieve this result for HTML5 websites?
I want to have strings in different languages, and just refer to them by an identifier.
You could store all of your languages in seperate JSON files. The problem would be that with Javascript you would be loading the language file after the page has loaded so you would see the original string briefly before the replacement is added.
HTML
<p>LANG:hello</p>
JSON file
{
"hello": "bonjeur"
}
Javascript
// Itentifier would be "hello"
// Element would be the actual element
// json would be the contents of the JSON file
element.text = json[identifier]
A better way would be to use a server side language such as PHP so the content is replaced before it is output to the browser.

How to implement different languages on html page

I am just a newcomer developing an app with html/css/js via phonegap. I've been searching info on how to make my app be displayed in different languages and Google doesn't understand me.
So the idea is to have a button on index.html that let the user choose the language in which the app will be displayed, in this case Spanish/English, nothing strange like arabic blablabla....
So I guess that the solution must be related to transform all the text that I load in html to variables and then depending on the language selected display the correct one. I have no idea how to make this, and Im not able to find examples. So that's what Im asking for... if someone could give some code snipet to see how html variables works and how should I save user language selection...
Appreciated guys!
This can be done by internationalization (such as i18N). To do this you need separate file for each language and put all your text in it. Search Google for internationalization.
Otherwise you can look into embeding Google Translate.
This depends on the complexity of language-dependencies in the application. If you have just a handful of short texts in a strongly graphic application, you can just store the texts in JavaScript variables or, better, in properties of an object, with one object per language.
But if you expect to encounter deeper language-dependencies as well (e.g., displaying dynamically computed decimal numbers, which should be e.g. 1.5 in English and 1,5 in Spanish), then it’s probably better to use a library like Globalize.js (described in some detail in my book Going Global with JavaScript and Globalize.js). That way you could use a unified approach, writing e.g. a string using Globalize.localize('greeting') and a number using Globalize.format(x, 'n1') and a date using Globalize.format(date, 'MMM d').

What javascript library/template engine to use in this case?

I have to make a invite your facebook friends module which fetches the names, photos of your friends and allows you to message 'em. I need this to look like a integral part of my website so I have to style it. I fetch the json with friends' ids, names etc. and want to put those values in certain html tags and attributes. How do I apporach this? I can make it in jQuery but want to avoid jQuery spaghetti code with ragu of strings and vars. What lib/template engine do you recommend me? Ease of use and weight are the most important things. The website has jQuery already included.
I can make it in jQuery but want to avoid jQuery spaghetti code with ragu of strings and vars. What lib/template engine do you recommend me?
I’d suggest to use no big additional lib or template engine – I’d just keep using jQuery, and embed one of the sprintf for jQuery implementations that are floating around the net.
So you can define your “HTML template” for your output in one location as one string, and than replace placeholders in that string with variable values while your looping over the data in jQuery.
If you don’t like any of the sprintf-Jquery-plugins out there, here is another very simple and short function that implements just the basic string placeholder %s (but more than that you most likely won’t need anyway): http://www.nczonline.net/blog/2011/10/11/simple-maintainable-templating-with-javascript/.
(And if you have to insert values in multiple places of your template string, than have a look at my comment on the bottom of that page, where if have proposed a simple adjustment to Nicolas’ function, that implements the “argument swapping” feature of PHP’s sprintf, so that you have to pass values to the function only once, but can use them in multiple places in your template string.)
The easiest way to do this is to use the Requests dialog. The first thing you need to do is create an app. Once you have this you should be able to use the JavaScript example on the request dialog page.

Javascript localization in .net

I'm trying to determine the best way to implement localization into one of our web apps. This app is going to have a large number of javascript files, which will need to be localized as well.
Localizing the .net code is straight forward enough. We have a file called WebResources.resx which contains all strings in english (our fall back language). Then we just add additional files with alternative localized information (eg: WebResources.es-mx.resx). Then, bam! .Net pretty much takes care of the rest.
Pretty sweet. But when it comes to javascript, not so fast. Reading on MSDN they recommend:
You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.
This seems like a maintenance nightmare that I'd like to avoid. Plus I'd like to avoid having to use the asp.net ScriptManager. So I got the bright idea of trying to use the resource files in my .js files. EG foobar.js:
function showGenericError(){
alert('<% =Resources.WebResources.JsGenericError %>');
}
This unfortunately does not work as the .NET does not seem to do any processing on .js files. So the next idea I got was from the answer on this thread. It recommended having a javascript file which contained all your language strings. This feels like a waist of resources since at run time I only need one language, not all of them.
This leads me to the solution I'm planning on implementing. I plan to have a generic handler that writes out JSON that is localized for the language the current user is in need of. Here is a sample of what the .ashx page will look like:
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "application/json";
StringBuilder json = new StringBuilder();
using (StringWriter jsonStringWriter = new StringWriter(json))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(jsonStringWriter))
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("genericErrorMessage");
jsonWriter.WriteValue(Resources.WebResources.GenericErrorMessage);
jsonWriter.WriteEndObject();
}
}
context.Response.Write("var webResources = " + json.ToString());
}
In the head of my pages I will have:
<script type="text/javascript" src="js/webResources.js.ashx"></script>
Then my js file will look like:
function showGenericError(){
alert(webResources.genericErrorMessage);
}
Almost seems too easy, right? So my question is, does this make sense? Am I missing a "gotcha" somewhere? What are the downsides? Is there a better way to do this?
I posted a similar question a while ago, and this is what I came up with:
Localize javascript messages and validation text
The advantage here is that you can share resources used in regular .net pages.
Your approach looks fine as well.
Here is the way i did it, just in case someone finds it useful.
I didnt want to put any Razor on JS, because of CSP i kept JS files separated from the cshtml.
So I added a element in the Shared cshtml, with the content of an array of arrays, each element of the array is a Key/Value pair with the name and the localized string as returned by Razor>
<meta name="resources" content="[
['name1', '#HttpUtility.JavaScriptStringEncode(Resources.name1)'],
['name2', '#HttpUtility.JavaScriptStringEncode(name2)']
]" />
Then in the js file, i convert this into a dictionary:
let livstrResMap = document.querySelector("meta[name='resources']").getAttribute("content");
livstrResMap = livstrResMap.replace(/'/g, '"')
let lioJSN = JSON.parse(livstrResMap)
let mcvcodResources = new Map(lioJSN);
Finally i use the localized string using the Format helper defined here
alert(mcvcodResources.get('name1'));

XML and Javascript: the right tool for the job?

For years I've been reading about XML and I have just not quite grokked it. Most documents I see about it simply explain the syntax (extraordinarily easy to understand) and say that it's portable: I've worked with Unix my whole life so the idea of putting things in plain text to be portable is hardly revolutionary. My specific question is that I have a document (my CV) that I would like to present to web visitors in several formats: as a webpage, as a pdf, or even as plain text. Is XML and Javascript the right approach to take?
What I need is for the document to be easily editable, conversion easy and just easy general upkeep. For example, when I publish a paper, I'd like to take less than five minutes to add the info and then have everything go automatically from there.
Give me your opinions: I also use LaTeX compulsively, so my current approach has been just to have my CV in LaTeX and to convert it to a web-page using LaTeXML. However, I sorta have the feeling that with everybody jumping up and down about XML and Javascript, that there might be something good to learn about it.
I would also like to simplify maintaining my homepage by not duplicating the same footer for every single page that I set up.
Thanks,
Joel
Edit: I'll also take any book recommendations!
I think this is a slight misunderstanding of the combination of JavaScript and XML.
XML, in and of itself is an excellent means of representing data. It's largely human-readable, and easily parsed with libraries in nearly every programming language. That is the main benefit of XML.
Using XML with JavaScript is certainly a solution, but I think it's a matter of the question you're asking. JavaScript can parse XML, and allow you to obtain and manipulate data from your XML document. If you want to grab data from a server without reloading your HTML page (synchronously or asynchronously), then using JavaScript and XML is a valid way to do that.
If you want to, however, display your XML as a webpage, you would likely be better off using XML and XSLT [wikipedia], or perhaps PHP and XPath, to transform the document into browser-readable HTML. On the other hand, you could use nearly any language to convert the XML to a plain-text file, rich text file, or store it in a normalized database.
To sum up, XML is a great way to store data, because it can be used in so many different ways, and by so many different languages. It's an answer to many different questions; you just have to figure out which questions you're asking.
To elaborate on my comment
The transformation to whatever output you desire is depending on how you store your CV on your server and whether you have the possibility to process it on the server. If you store it in XML, you can transform it to desired (binary) output using server based tools - that would for php be pdf and word (on windows server platform) for example. XML would be interesting from a mark-up point of view since it would make it clear where the table of contents, headers, lists of experience and so one would be found.
JavaScript cannot transform something into PDF or word, that has to be done on the server. What javascript can do is to get a text from the server in XML or JSON using AJAX and manipulate this into what the user sees on the screen. For XML that can be done with XSL(T) too. If you want for self-education purposes to use JavaScript, JSON is very nice since it is in my opinion more readable than XML and it creates a populated javascript object with the least work.
Footer in javascript: in the page have
<script type="text/javascript" src="footer.js"></script> and in footer.js, you can for example do
var footerText = 'Here goes whatever you want';
document.write(footerText);
Comparison between XML and JSON
I've got a webpage with browser-side XSLT transformation up and running for years. It's a playground, only some words in german. See how easy it is to build this on heese.net/test. You can switch between "Beispiel" (=Demo) and XSL. The sourcecode of the page in the iframe is the XML. You can do this serverside with 3 lines of PHP-code.
On Javascript: you can use it with XSLT and I show this on my site, but it can't interact. First the XSLT builds an HTML page out of your XML data and after this job is completely done the Javascript in the resultig HTML document begins to work.
Parsing XML with Javascript is a different task.

Categories

Resources