问题
I am trying to localize my Javascript files. For instance, I would have:
var count = 0;
$('#choices .choice').each(function(i) {
$('input', this).each(function() {
count++
$(this).attr('placeholder', '@Message("placeholder.choice") ' + count)
})
})
This would obviously work if the Javascript file is inside the Scala HTML template but I would prefer to have it in a dedicated file.
To begin with, I am wondering if it is a good idea: what about caching file if it's content may change? In this case, there is a single parameter: having it in the URL would solve this problem? Eg: /assets/javascripts/:lang/my-file.js
.
And the real question is: is it possible to do that using Play! framework? It does not seem that Javascript templates are supported (or I missed something). Is there a way to do it correctly?
回答1:
Actually you don't need to translate your JavaScripts dynamically, it's reduntant waste of resources, instead prepare static JS files like messages.en.js
, messages.de.js
etc and include required file basing on the user's language directly into the view.
Here you have some description how to make it easy (JavaScript approach)
回答2:
There is a module allowing javascript internationalization using the same mechanism as in Play templates, have a look at : https://github.com/julienrf/play-jsmessages
This will definitely fits your needs. I use it for a while know with success. You can expose your translations through a javascript file and then use browser caching with a proper fingerprinting configuration.
来源:https://stackoverflow.com/questions/15763655/dynamic-javascript-using-scala-template