i18n in React with .properties files - javascript

I am in the middle of (large)app rewrite into Reactjs-redux and internalization is next problem.
Ive been looking at some currently available libraries (redux-react-i18n , 18n-react) but none of them seems to fit.
Why ? Because my localized strings are stored in separate .properties files and this cannot be changed. But there is a possibility generate whatever format from this in compile time
Example en_US.properties:
key1=This is a constant string
key2=This is a string with {parameter}
....
and similar with de_de.properties file and so on
Also language can be change only on page refresh so this is making it little bit easier
My question is how to approach this problem. My first naive approach is generate some static constant js object available in app globaly but im feeling thats against javascript best practises also no idea how to deal with parametrized strings
As im fairly new to javascript id like to hear any ideas

In case somebody has same problem
I ended up writing script converting .properties files into json files
Then in React code i created HOC component wich gets keys(or namespaces depends on how you organize your json files) as parameter and fetches values from server
These keys are usually for whole page but sometimes also for single component if it makes sense
All it takes is one more HTTP request you can also cache result
Hop it helps

Related

How should you store a multi-line text file? As a text file or js file?

I am building a discord bot using discord.js and NodeJS. I have multi-line (about 20 lines long) message that I wish to send to a channel for a certain command. For improving the readability of the source code, I thought that I would use a different file for storing this message. Initially, I thought I would move the contents to a text file and then use fs.readFile() to read the contents. But, now, I think it's better to store the contents in a variable (lets say multiLineString in another js file (say message.js and export this variable from the file. That way, I could directly get the contents using require('./message.js').multiLineString. But I don't know if this is a good practice as I am new in NodeJS. So, which is the correct or better method, in terms of both memory and performance?
You should consider storing these messages in JSON files. (go read about JSON). They're safer than pure Javascript for this purpose: You have to totally trust the content of files you require(). But files you read and then do JSON.parse() on will just make that function throw an error if they're wrong.
The real question here is, whether you want to be able to edit that message on purpose (without having to restart your server) - or not.
If not, there's nothing really wrong with any approaches you mentioned. The only thing that you'd rather avoid is rereading the text on each request (especially with a synchronous operation). Slightly more time will be spent on converting the text read from a file system into a proper JS value, but that's really negligible.
However, if message itself should be dynamic and you want to be able to update it without having your server restarted, that's different. And if that's the case, strive for how easy is for admin to work with that file, not for how performant the operation is; you'll have to spend time on reading this anyway. The best you can do is to check some kind of 'fast' marker - for example, update time (if we still talk about the files) - before actually attempting to reread it.

How to read local client side text files, without using any html input/search elements

The purpose, game programming, as you may have guessed, why else right?
How is it actually possible to read in values from a text file, so that those values can be then on wards used in the game? I have searched for hours on this topic.
example: each text file line token, will be read and passed as the different arguments into the constructor of each object during its instantiation via for loop. A common practice. Its Too expensive to store that much data at any given time in an array I would suspect.
In java this is dead simple using the Scanner object.
Any suggestions are appreciated thanks. I guess all I am asking is, is it even possible?
As Roland Starke said, the array will probably take up less memory than the objects you construct from it... So it is perfectly fine to have all the information in a JSON file for instance, which you load from your server.
If you want to avoid transfering all the data every time, you would need to use the right caching headers so that the data can be cached by the browser.

ternJS - Generate JSON type definition file

ternJS have several. JSON files defs which contains the definition of librarys. Can someone explain to me how I can best generate my own to my javascript libraries / or only definition objects?
I can not see that there is no common procedure for this?
There's a tool for this included in Tern. See condense at http://ternjs.net/doc/manual.html#utils . It runs Tern on your file and tries to output the types that it finds. It's far from flawless, but for simple programs it works well. For files with a complicated structure or interface, you'll often have to hand-write the definitions.
There are three ways I have thought about to solve your problem:
Using Abstract Syntax Tree Parser and Visitor
One way to solve your problem would be to use abstract syntax tree parser and visitor in order to automate the task of scanning through the code and documenting it.
The resources here will be of help:
-http://ramkulkarni.com/blog/understanding-ast-created-by-mozilla-rhino-parser/
-What is JavaScript AST, how to play with it?
You usually use a parser to retrieve a tree, and then use a visitor to visit all the nodes and do your work within there.
You will essentially have a tree representing the specific library and then you must write the code to store this in the def format you link to.
Getting a Documentation Generator and Modifying
Another idea is to download the source code for a documentation generator, e.g. https://github.com/yui/yuidoc/
By modifying the styling/output format you can generate "documentation" in the appropriate json format.
Converting Existing Documentation (HTML doc) into JSON
You can make a parser that takes a standard documentation format (I'm sure as Javadoc is one for java there should be one for javascript), and write a converter that exctracts the relevant information and stores in a JSON definition.

Good practices for writing HTML in Javascript

I was wondering about this if people have strong opinions about the best way to generate HTML on the fly, especially with Ajax based applications.
Do you just create the HTML code using server side scripting and then send it out to the page or perhaps just return a JSON string and let Javascript do the job.
In my personal opinion, the first way ties the presentation layer way too much to the logic and makes it harder to change and a nightmare to maintain. The second way, although is my preferred method, also becomes a nightmare to maintain when the complexity of the project grows.
I was thinking of using a Javascript templating system as another layer, just to make the code more robust and less rigid. Anyone has good ideas of a light and really good JS templating system?
http://ejohn.org/blog/javascript-micro-templating/ is a devilishly brilliant hack for this. End result is very clean.
I too prefer a JSON response with client-side HTML creation logic.
Unfortunately, most real-world client-side HTML writing scripts are broken, containing many HTML-injection flaws that can easily become cross-site-scripting security holes. I think the belief is that because you're talking to your own server rather than directly to a hostile user you're somehow ‘safe’ and can get away without correctly strings when interpolating them into HTML. Which is of course nonsense.
I always see stuff like:
$('#mydiv').append('<em>Deleted '+response.title+'!</em>');
or:
mydiv.innerHTML= '<p>Renamed to '+response.name+'</p>;
or indeed Resig's microtemplating hack, where there is no HTML-escaping done by default. Come on, people! We've only just started cleaning up the legacy of broken PHP scripts serving up server-side XSS, now you want to introduce a whole new massive range of client-side XSS exploits?
Sigh. That's the Lure Of Strings. We think we understand them and can sling them together willy-nilly. But strings are treacherous, with hidden contexts and escaping requirements. If you must generate HTML on the client side you will need a function like this:
function h(s) {
return s.split('&').join('&').split('<').join('<').split('"').join('"');
}
mydiv.innerHTML= '<p>Renamed to '+h(response.name)+'</p>;
But personally I prefer DOM methods. Like with parameterisation for SQL, using the DOM methods takes the string-slinging out of the equation by talking raw strings directly to the components that will consume them. OK, the problem with the DOM is that it's rather verbose:
var p= document.createElement('p');
p.appendChild(document.createTextNode('Renamed to '+response.name))
mydiv.appendChild(p);
But you can always define helper functions to cut down on that, eg.:
mydiv.appendChild(makeElement('p', {}, 'Renamed to'+response.name));
(The new element creation stuff in jQuery 1.4 uses a similar style.)
+1 year ago, we started a new web app, and needed a way to render HTML from JSON data, in the browser.
We wanted it as fast as an XML/XSLT transformation.
Our answer to that was the JS template engine PURE.
Unlike most of the JS templating libs around, it keeps the HTML untouched(no strange tags at all) and except a few notations, it doesn't bring a new language to learn, only JS and HTML.
The way I use it:
Build the static HTML directly in the page
Then add the JS logic step by step, and the HTML becomes alive progressively
Once you get used to it, both HTML and JS can have a safe separate development life, and can be split between a designer and a JS developer job
We had a system where a lot of data was being passed as JSON from the server and then handled through a javascript templating engine on the client side. In .Net 4.0 (maybe even 3.5 sp1, i am not sure), this can be done using Client Templates.
I would prefer passing JSON over sending html. Its always good to keep data and view separate.
If you want to preserve the MVC framework, you should let your template framework do the templating.
The AJAX should only perform the server request, which performs all DB and business logic and then returns the URL to the template that should be loaded.

Best practices for returning and displaying data from AJAX calls

I have some jquery/php interaction set up on a page. It submits some data to the server and gets back records of data which are then to be aligned on the page for comparison and possible action beyond that.
My question is what is the best practice for returning the info and then displaying it?
Return JSON object and then create
html on the fly with js and display
the data?
Return JSON object and then
put that data in already created
containers for the data on the page?
Return pure html from the server and
just put that on the page?
I was rolling these through my head last night and couldn't really figure out if one way would be better for any particular reason.
I'm not a js guru so wasn't really sure the pros/cons and caveats to these different methods.
I think it ends up depending on your app.
Pure HTML is the easiest, you just drop in in place and viola. JQuery makes it a breeze to add the proper events and what not.
However, whenever I've used AJAX it's always evolved into returning JSON and building elements on the fly. If you are populating a tree for example, it may become messy to get the proper nesting. This forces you to have to do client side code anyway at which point simply using JSON from the start is cleaner.
Also, If you plan to use the data calls from other pages then using JSON is the way to go because the HTML will bee fixed.
This completely depends on the way you have things set up in your application. I, for one, prefer to return JSON (second approach in your list), because I have an 'error code' parameter that I check in onSuccess function before updating the content on the page, and if it's not zero then I notify the user of the error, including the error message that came back from the server (server-side validation, database timeout, etc.).
I think you're missing a perfectly valid option, one which I use often. This is my typical schema and it has yet to fail me... :-)
Here's the basic jQuery template I use:
$(function() {
$.getJSON('/some/page',{foo:bar,bar:foo},function(json) {
if(json.outcome == 'success') {
$('body').prepend(json.html);
} else {
// Somehow let the user know why it didn't work
alert(json.error);
}
});
});
Here's the basic backend (PHP in my case) structure I use:
<?php // Page: '/some/page'
/* Blah Blah Blah... do whatever needs to be done... */
// If everything turns out okay (assuming '$output' is the HTML
// you want to display...
echo json_encode(array('outcome'=>'success','html'=>$output));
// If something goes wrong... just do:
echo json_encode(array('outcome'=>'error','error'=>'Uh oh... something is broken'));
Naturally, you'll want to be more specific with your error by putting them into some variable or something. But, you should get the idea. Also, of course you can add more information to the json output. You can have some pre-made HTML and also some other information like a 'success notice' or a new class name for some element, I dunno... whatever... the possibilities are endless.
Anyways, the reason I choose this route is because it's usually faster (based on my experience) to append pre-made HTML to the DOM rather than looping over JSON and inserting the stuff unless it's just, like, a bit of text to replace into an element. But, the method I've shown is, IMO, the best of both worlds. You can attach HTML as a string to one of the JSON properties.
Happy jQuerying :-)
The "possible action beyond that" part of your question makes a big difference. If you need to do other things with the data besides display it, returning as JSON is a clearly better option because you can work with the data as a native JavaScript object instead of having to traverse the HTML DOM. If all you ever intend to do is display it, I don't see any reason to go through the trouble of building that display in JavaScript; just build the HTML in your presentation layer on the server.
This came up recently and possible a dupe: The AJAX response: Data (JSON, XML) or HTML snippet?.
If you are going to be creating HTML then you may as well be returning HTML directly and inject it into the DOM. However, there are times you need to work with objects which is where JSON comes in handy.
If you return a Person object for example then you can greet Person.Name and show Person.Preferences which is really handy. It depends on your design but the general considerations should be to keep HTML out of Javascript unless you're building RIA.
I have used all three and have come to the conclusion that returning HTML is better when introducing new elements to a page.
My experiance is that when building HTML with javascript I am usually replicating work that will have already have been done for the non javascript user journey.
I still prefer parsing json for updating existing elements or creating javascript only functionality. I tell myself this for bandwidth, but I think it just because I love javascript.
As a forth option, I read a great post about how Flickr deal with vast quantities of data with string concatination. Basically just parse a big o' string down the pipe and chop it up on the client. This significantly reduces the on the server, with only a marginal increase on the client.
Returning pure HTML is the best solution. For the most part gzip should neutralize any difference in bandwidth, and rendering via javascript on the client can be slow if the client is a crappy machine. Finally, writing javascript to render HTML is hard to work with compared to using something nice like a view if you use MVC.

Categories