Javascript localization in .net - javascript

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'));

Related

Go templating engine that also runs in the browser

I'm developing a web application with Go on the server, and the router will use PushState, so the server will also have to be able to render my templates. That means that I'll need a templating engine that works with Go and Javascript. The only one I've come across so far is Mustache, but it doesn't seem to be able to handle lowercase properties of structs, and there also doesn't seem to be a possibility to provide custom names like JSON:
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
So, is there a templating engine that is available in both Go and JavaScript, and that can handle lowercase struct properties?
As the comments above state, you can't expect any 3rd party library to be able to read lowercase properties on your struct, but it appears you are trying to use tags to represent alternative representations of your struct (as you can with the encoding/json library).
What you can do is use something like github.com/fatih/structs to convert your structs to maps and then range through to lowercase all of your keys (copying the values and removing the uppercase versions) and pass it into mustache.Render() as your context. If you want to use struct tags like the encoding/json library does, you'd have to use the reflect package and write a struct-to-map function that takes into account the tags on the struct (basic example given in the documentation here). There are some SO answers on how to write a struct-to-map function using reflection, which you can improve upon to add struct tag handling as you need.
To answer your question, I don't think this is something a current templating library does that also works with javascript, but it shouldn't be too hard to get working with mustache given the idea above.

Javascript File Name Encryption and Referencing

I want to change the JavaScript names in my application for additional security like facebook and google plus suring deployment.
Is there are an application or a library that can change the JavaScript file names and reference them in the my view (written in php) and JavaScript files.
EXAMPLE OF THE DESIRED EFFECT
Change this (Before Deployment):
In folder: js/myfunction.js
In file:<script type="text/javascript" src="https://mysite.com/myfunction.js"></script>
To this (After Deployment):
In folder: js/PuKJS78UyH.js
In file: <script type="text/javascript" src="https://mysite.com/PuKJS78UyHK.js"></script>
Instead of obfuscating and encryption you should think about optimization. Couple things that you could do:
Combine all common JS files in one file (minimizes number of requests and also solves your problem - there will be no file names to obfuscate)
Minimize JS - it's faster that way and takes less space (and in addition it becomes unreadable)
This tool looks like a good place to start: http://code.google.com/p/minify/
You should not depend on JavaScript encryption. It is not safe, and might be hacked in a short time. Using sever side languages like PHP is much safer than JavaScript.
However, if you would like to perform a simple base-64 encoding in JavaScript, for which normal people will not able to read, you are lucky, it doesn't need any library. \(^o^)/
Just use btoa() for encoding, and atob() for decoding. Then you can create a <script> tag using the encoded URL.
Read more in MDN: window.atob
Example:
var txt = "myfunction.js";
var encode = btoa(txt);
var decode = atob(encode);
console.log( encode ); //return "bXlmdW5jdGlvbi5qcw=="
console.log( decode ); //return "myfunction.js" (orginal)
//Do whatever you want with the encoded text, like
$("<script src='/js/"+encode+".js' type='text/javascript'></script>")
.appendTo("head"); //dynamically adding an script tag using jQuery
Demo: http://jsfiddle.net/DerekL/JWSUs/
Result:
Result from jsFiddle. You can see that "myfunction.js" is encoded to "bXlmdW5jdGlvbi5qcw==", which normal people will not be able to read.

Multi language support

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.

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.

Javascript and Translations

I have a PHP application that makes extensive use of Javascript on the client side. I have a simple system on the PHP side for providing translators an easy way to provide new languages. But there are cases where javascript needs to display language elements to the user (maybe an OK or cancel button or "loading" or something).
With PHP, I just have a text file that is cached on the server side which contains phrase codes on one side and their translation on the other. A translator just needs to replace the english with their own language and send me the translated version which I integrate into the application.
I want something similar on the client side. It occurred to me to have a javascript include that is just a set of translated constants but then every page load is downloading a potentially large file most of which is unnecessary.
Has anyone had to deal with this? If so, what was your solution?
EDIT: To be clear, I'm not referring to "on-the-fly" translations here. The translations have already been prepared and are ready to go, I just need them to be made available to the client in an efficient way.
How about feeding the javascript from php? So instead of heaving:
<script type='text/javascript' src='jsscript.js'></script>
do
<script type='text/javascript' src='jsscript.php'></script>
And then in the php file replace all outputted text with their associated constants.
Be sure to output the correct caching headers from within PHP code.
EDIT
These are the headers that I use:
header('Content-type: text/javascript');
header('Cache-Control: public');
header('expires: '. date("r", time() + ( 7 * 24 * 60 * 60 ) ) ); // 1 week
header("Pragma: public");
I usually load the appropriate language values as a JavaScript object in a separate file which the rest of my code can reference:
var messages = {
"loading": "Chargement"
}
alert(messages.loading);
The language library will be cached on the client side after the first load and you can improve load efficiency by splitting values into separate files that are loaded based on context: e.g. a small library for public operations, an additional one behind a login, etc.
What you are looking for seems to be AJAX (client and server exchanging asyncronous requests using Javascript).
If you're looking for something ready-made, take a peak at Google Translation AJAX APIs.
I have never personally had to do this, but my first guess would be to reference a third party library. I believe the Google AJAX API might have just the tool to do this, and since the library is through Google, the javascript file will not be downloaded from your site.
Try digging through the following site for a bit: http://code.google.com/apis/ajaxlanguage/documentation/
Let me know if that helps you out. I might be interested in implementing something similar for the website I manage.
Good Luck,
C
I like Pim Jager's answer, and have done that myself. If you don't want to have the PHP generate the JavaScript for you (say, for performance reasons), you can have a master copy of the JavaScript libs, and when they change, run a translation program to generate a version of each lib for each language. Then just have the PHP put the right version for the current user in the script tag it sends.
I worked on a system that needed both heavy localization and heavy branding for different customers. What we did was anything that got sent to the screen had a unique macro, like [3027] (or something like that). Then we had a bunch of locale and branding files that had entries for each macro code, and the text to substitute for each macro. A program would loop through all the source files and all the languages and make the substitutions.
We found we also needed some functions for localization, for monetary amounts, dates, times, etc. It all worked pretty well.
We found we needed one more important thing: A tool to go through all the language files and make sure they all had all the necessary codes. Big time saver.

Categories

Resources