jquery-i18n-properties / jquery-i18n-properties Goto Github PK
View Code? Open in Web Editor NEWlightweight jQuery plugin for providing internationalization to javascript from ‘.properties’ files
License: MIT License
lightweight jQuery plugin for providing internationalization to javascript from ‘.properties’ files
License: MIT License
I didn't like the idea of having to edit the javascript every time I add a new key so I tried to come up with the following solution to dynamically load all HTML elements based on the translation key. Here's the HTML for a complex types with parameters.
This also allows for dynamically passing the params from the HTML and not via javascript. by using an additional <span class="param">
inside the element I want to translate
HTML
<span translate="yes" class="msg_multi_placeholder">Welcome <span class="param">Jacob</span>. Today is <span class="param">28-12-2014</span></span>
Below is the javascript I'm using for this:
javascript
function updateSelected(translationKey) {
var params = '';
$('.' + translationKey + ' .param').each(function(i, param) {
params = params + ', \'' + param.textContent + '\'';
});
var translationCommand = '$(\'.\'+translationKey).empty().append($.i18n.prop(translationKey'+ params + '));';
eval(translationCommand);
}
function updateAll() {
var keys = Object.keys(($.i18n.map));
$.each(keys, function(i, key){
updateSelected(key);
});
}
messages_es.properties
msg_multi_placeholder = Bienvenido <span class="param">{0}</span>. Hoy es el <span class="param">{1}</span>
I must admit, this is not very neat. I would like to find a solution to make the property file a bit neater, a double placeholder for one parameter seems a bit much.
Hi,
I tried using the plugin without an existing country file.
The callback with the async option did not work. I figured out, that the callbackIfComplete is not called, since the files are not "completly" loaded.
It works with adding:
else
nextFile();
after row 328 https://github.com/jquery-i18n-properties/jquery-i18n-properties/blob/master/jquery.i18n.properties.js#L328
Best regards,
Fabian
There are 3 active "HERE" console log messages on the minefield file.
On iOS under Cordova the synchronous requests to local URIs may trigger successes even if the requested file is not present. This will leave the language variable in line 93 uninitialised which leaves the code crashing.
I've found some debug messages "console.log" in the minified version.
console.log("HERE1");
Just what the title says. Right now when the event is handled, the nodes that are being made visible are still 'display:none' so they are not easy to find in the event handler.
Hello
I have the following structure for a Spring Web App
To create a .properties files in many languages I use: essiembre/eclipse-rbe
For example message.properties
contains:
id = Campo ID no puede estar vacio.
and message_en_US.properties
contains:
#Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/)
id = Field ID can't be empty.
My code about jquery-i18n-properties is:
jQuery.i18n.properties({
name: 'message',
path: '../resources/jquery.i18n.properties/messages/',
mode: 'both',
callback: function() {
console.log(jQuery.i18n.prop('id'));
}
});
When I execute the code on Opera and Chrome all work fine.
But just in Firefox 43.0.2 (Mac) I can see the following:
If I do click for each error syntax in the right part (blue text) I can see the following respectively.
id = Campo ID no puede estar vacio.
And
#Generated by ResourceBundle Editor (http://essiembre.github.io/eclipse-rbe/)
id = Field ID can't be empty.
I don't know why that error is arising
Some ideas?
Thanks
Hello all,
When I try to pass language dynamically from select dropdown list, It shows following error
Uncaught TypeError: Cannot read property 'properties' of undefined at changeLanguage
Where changeLanguage is my function as follows:
function changeLanguage(lang) { lang = lang || "en_EN"; // if no language is set, use browser default jQuery.i18n.properties({ path : 'language', mode : 'both', language: lang, name: 'Messages', callback: refresh_i18n }); }
Following is the pictures of it:
What is wrong with the code?
Please do suggest!
Thanks
I wonder f it's possible to turn off escaping.
I want to insert a text with html tags.
Line 22. console.log is used without testing for window.console.
I have a simple properties file that has the sole entry:
event_heading = Events for {0}
This renders correctly in the UI via the following:
jQuery.i18n.prop('event_heading', formattedDate);
However the console reports a syntax error on line 1.
I see that the plugin attempts to load {path}/languages.json ... yet I don't see any documentation detailing what this file should be or what it should look like. Have I missed part of the documentation?
Suggestion:
for(i=0; i<files.length; i++) {
=>
for(var i=0; i<files.length; i++) {
Hello may possible add suport to npm?
A currently use a fork version because it.
https://github.com/michogar/jquery-i18n-properties
If need help, i can contribuit with this.
thanks,
Pedro Sanchez
Hello,
I can see that the plugin loads browser language translations by default.
In fact this is not always needed. The developer might want to load only translations supported by application and not by browser.
I would like to suggest additional option:
useBrowserLang. It would enable or disable browser language loading.
I am aware that when the resource is not present it will not be loaded anyway, but there is no need to hit not existing resource.
Problem:
The language files are loaded into javascript data structures every time a page is load. This impacts performance and slows down the page load.
For example, if we are using a 300KB property file, the browser may take 300 - 400 ms to load this file. This load time is repeated for each language file loaded. In a typical case, we are fetching 3 files every time we load new page, so the total load for these 3 files can go up to 800 ms.
I solved this issue by storing the parse language files in sessionStorage, and on every page load, it will look for and try to load
Only the first load will take sometime to fetch the files, but after stores the files in the sessionStorage it will take 10 -20 ms for each file.
Here's a code snippet
/** Load and parse .properties files */
function loadAndParseFile(filename, settings) {
i18nfName = 'i18nmp'+filename;
i18nmp = sessionStorage.getItem(i18nfName);
if (i18nmp != null){
$.i18n.map = JSON.parse(i18nmp);
return;
}
$.ajax({
url: filename,
async: false,
cache: settings.cache,
contentType:'text/plain;charset='+ settings.encoding,
dataType: 'text',
success: function(data, status) {
parseData(data, settings.mode);
sessionStorage.setItem( i18nfName, JSON.stringify($.i18n.map));
}
});
}
I have same problem with this post.
#25
Trying async: true settings, but haven't clear warning.
And I inspected the code in latest 1.2.0 version.
But, in ver.1.2.0, settings.async seems to be ignored.
** ver.1.2.0 **
function loadAndParseFile(filename, settings) { $.ajax({ url: filename, async: false, cache: settings.cache, contentType:'text/plain;charset='+ settings.encoding, dataType: 'text', success: function(data, status) { parseData(data, settings.mode); } }); }
** latest code **
function loadAndParseFile(filename, settings) { $.ajax({ url: filename, async: settings.async, cache: settings.cache, dataType: 'text', success: function (data, status) { parseData(data, settings.mode); callbackIfComplete(settings); }, error: function (jqXHR, textStatus, errorThrown) { console.log('Failed to download or parse ' + filename); callbackIfComplete(settings); } }); }
When do you release async true version.
Just started using this and am unsure how this can be useful if you have to use async to get it to work at all (without getting sync warnings). For example:
$.i18n.properties({
path: base_url + '/js/languages/',
mode:'map',
language:'en_GB',
async: false
});
alert($.i18n.prop('msg_hello'));
This doesn't work unless I set aysnc: false
.
So basically this library is unusable unless all your translations you want to do are run in an asynchronous manner?
"Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."
is what I get every time I try to use a call with jquery-i18n-properties. I just cloned the repo and opened up the index.html file locally. Am I missing something?
Add namespacing for translations. If you have two pieces of code on the same page using i18n properties you can get the scenario where names can clash. This doesn't happen in java as you can put i18n in packages. Currently, in this library, you need to modify your resource keys with the package hierarchy, which is a bit of a burden.
It's possibile to install this plugin via bower?
thx
Hello
I am using jQuery.i18n this way
jQuery.i18n.properties({
name:'Messages',
path:'...',
mode:'both',
cache:false,
language:'<%= client_language %>',
checkAvailableLanguages: true,
encoding:'UTF-8',
async: false,
callback: function() {...}
}
and I am loading a French property file, UTF-8 encoded.
The issue is that apostrophes like in "Donneur d'ordre" aren't displayed. The text appears as "Donneur dordre".
Any ideas how I could achieve a correct French display?
Thank you very much for your advice.
Klaus
Languages are not loading in IE when I use jquery 1.11 version
Language codes are only currently normalised when retrieved from the navigator object. This leaves open the possibility of calling code supplying a badly formed code and language download subsequently failing.
Sometimes in Chrome Browser and Chrome WebView for Android the navigator.languages property exists and is an empty array. This causes the following line to error: https://github.com/jquery-i18n-properties/jquery-i18n-properties/blob/master/jquery.i18n.properties.js#L429
When trying to perform toLowerCase on undefined.
Android 7.1.2
Chrome 57.0.2987.132
Hello;
I try calling
jQuery.i18n.properties({
name: 'Messages',
callback: function(){ alert( org.somekey ); }
});
But I am getting an error : TypeError: jQuery.i18n is undefined
What I've done is :
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type='text/javascript' src='js/jquery.i18n.properties-min.js'></script>
<script>
jQuery.i18n.properties({
name:'Messages',
path:'bundle/',
mode:'both',
checkAvailableLanguages: true,
async: true,
callback: function() {
alert(t_1);
//app.initialize();
}
});
</script>
Where have messed up?
Does the $.i18n.prop () function get the value of the value of the array as a parameter to support it?
$.i18n.prop(key, arr);
$.ajax({
url: indexFileUrl,
async: false,
cache: false,
success: function (data, status) {
languages = data.languages;
}
});
why not async?
Hi to all.
When running my loadConfig() function it really is trying to load two files from de server.
config.properties
config_.properties
my config.properties doen't exist , and give me a 404 Not Found error,
There is any way to force only one? (config_.properties)
this is my code.
function loadConfig() {
$.i18n.properties({
name:'config',
path:'properties/',
language:'',
cache: true,
mode:'both',
callback: function(){
console.log('properties loaded');
}
});
}
In GC 44.0.2403.130 (64-bit) (on Mac OS), navigator.language is reports en-US
regardless of whether I have specified a different language in the browser settings. (I have specified Spanish as the first preferred language and English as the 2nd).
It happens in:
$.i18n.browserLang = function () {
return normaliseLanguageCode(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);
};
In the Chrome JS console, I get:
> navigator.language
en-US
> navigator.languages
["es", "en-US", "en"]
Anyway, the plugin should use navigator.languages, not navigator.language so the languages can be loaded in the preferred order.
Hello
I am working with jquery-i18n-properties
and I get how a warning the following messaging:
The problem has been reported here:
jquery has deprecated synchronous XMLHTTPRequest
Check the following answer (mostly check the comments)
Thanks.
Hi!
I put my language properties file under resources/bundle/Messages_**.properties
I imported the plugin:
<!-- Internacionalização --> <script src="resources/js/jquery.i18n.properties.min.js" type="text/javascript"></script>
and loaded in my .js file:
$(document).ready(function() { jQuery.i18n.properties({ name: 'Messages', path: 'resources/bundle/', mode: 'both', language: 'en', async: true, callback: function() { console.info('Iniciando internacionalização'); $('[data-i18n]').each(function(e) { var tagName = $(this).get(0).tagName; switch (tagName) { case "A": $(this).html(jQuery.i18n.prop($(this).attr("data-i18n"))); break; } }); } }); });
but I`m getting the following error:
jquery.i18n.properties.min.js:9 Uncaught ReferenceError: settings is not defined
at Object.h.i18n.prop (jquery.i18n.properties.min.js:9)
at HTMLAnchorElement. (default.js:35)
at Function.each (jquery.min.js:2)
at n.fn.init.each (jquery.min.js:2)
at Object.callback (default.js:31)
at v (jquery.i18n.properties.min.js:1)
at n (jquery.i18n.properties.min.js:1)
at jquery.i18n.properties.min.js:1
at Object.success (jquery.i18n.properties.min.js:2)
at i (jquery.min.js:2)
what am I doing wrong?
Hello
I'm using .net framework 4.6.2 and i can't make this work.
I can't load or parse my .properties file.
Is this working with .net mvc ? .net rooting problem ? what's the good path ? there is no example here
p�ginas
I trying use jquery-i18n-properties for multilanguage, if change language in page, succses. if open fancybox, content in fancybox, not translation, conten default
if any key is not found in properties file it should not throw error. Exception should be handled by checking 'value' before accessing this object in the plugin.
from line no 237 the below changes is required to handle the exception in jquery.i18n.properties.js
if (value && value.length === 0) {
return "";
}
if (value && value.length == 1 && typeof(value[0]) == "string") {
return value[0];
}
var str = "";
var len=0;
if(value){
len = value.length;
}
for (i = 0, j = len; i < j; i++) {
I have integrated example of jquery-i18n-properties.
It's working fine for Messages.properties and Messages_es_ES.properties.
But when I tried to load arabic then it shows ?????? symbol.
I have created Messages_ar.properties file with arabic content in it. when I pass value ar
to language then it shows me ?????
only..
Am I missing something ?
Using a number in resource key to start a module, makes all next entries unreadable. Same goes for starting with '-'. Keys have same problem also when there are multiple '-' in a key part.
You can use number like:
module.field.label1 = label1
module.field.label_2 = label2
module.field.label_field_module = label3
But when using it like below, is not working. It's return first element as it should, but every next one will be returned as -> "[key]", in this example "[module.field.label.2]"
module.field.label.1 = label1
module.field.label.-bc2 = label2
module.field.label.la-fd-dfs = label3
If resolving issue is too time consuming, even simple repair, just to don't accept this key and decline single rows would be much helpful. Now you have to go through whole document fixing it line by line, becouse every mistake makes all following resources not working.
The variable: "var cbSplit; " declared as global variable is creating a memory leak in IE11.
The page where the library is used will always leak in IE11 because the IE garbage collector will not garbage it.
In order to confirm the leak I added a temporary function cleancbSplit to nullify the cbSplit variable and the memory leak was gone.
var cbSplit;
// avoid running twice, which would break cbSplit._nativeSplit
's reference to the native split
if (!cbSplit) {
cbSplit = function(str, separator, limit) {
.....................
cbSplit._nativeSplit = String.prototype.split;
window.cleancbSplit = function() {
cbSplit = null;
}
}
I have two properties files, Messages.properties (english) and Messages_fr.properties.
My languages.json looks like:
{ "languages": [ "", "fr", ] }
With async: true
in the initialisation, and requesting french, about 50% of the time I still get english messages. It seems to depend on the order that the properties file is loaded.
If the webserver log has:
"GET /plus.codes/i18n/Messages.properties?_=1478851360136 HTTP/1.1" 200 4048
"GET /plus.codes/i18n/Messages_fr.properties?_=1478851360137 HTTP/1.1" 200 4479
then it's all good - I can get the French text. But if the requests are ordered:
"GET /plus.codes/i18n/Messages_fr.properties?_=1478851291009 HTTP/1.1" 200 4479
"GET /plus.codes/i18n/Messages.properties?_=1478851291008 HTTP/1.1" 200 4048
Then even if the language requested is "fr" I still get the English messages.
Changing to async: false
appears to fix this.
Due to network/browser issues you can load and parse the property files in the worng order.
For example, in the code you first load default ".properties" file then the "_xx.properties" and finally the "_xx_YY.properties" file. But this could not be the real order and due to network issues you could load the ".properties" in the last position.
In this case you will see the page in the wrong language (the default), because the load method just overwrite the properties no matter their precedence is.
The load and parse method must check if there are other languages previously loaded to avoid concurrence issues.
I have a setup where multiple portlets are rendered inline into the same page. Each of these emits the jquery library as it has its own requirements.
One of these uses i18n-properties. Unless it is the last one to be rendered, the subsequent loading of jquery overwrites the i18n registration.
I end up with something like this:
<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>
...
<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="/my-calendar/scripts/jquery.i18n.properties.min.js"></script>
...
<script type="text/javascript" src="/library/webjars/jquery/1.11.3/jquery.min.js"></script>
This then causes:
jQuery.i18n is undefined
If the webapp using i18n-properties is the last one to be rendered, then it works, but this is not guaranteed as it is a portal.
I am wondering if this could be resolved via namespacing the invocation of i18n-properties in the specific portlet? I currently load it like this:
$(document).ready(function() {
jQuery.i18n.properties({
name:'Messages',
path:'/my-calendar/bundle/',
mode: 'both',
cache: true
});
...
Add trailing / to path is there isn't one. If your path lacks a trailing slash the download fails.
If one uses a script with the defer attribute to invoke synchronous property loading with jquery-i18n-properties then it may fail in Firefox.
Ex:
<script defer src="jquery.js"></script> <script defer src="jquery.i18.properties.js"></script> <script defer src="support_file_that_invokes_jquery_i18n_and_creates_helper_functions.js"></script> <script defer src="file_uses_helper_functions.1.js"></script> <script defer src="file_uses_helper_functions.2.js"></script> <script defer src="file_uses_helper_functions.n.js"></script>This may be fixed in future versions of Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1212696#c33
Not sure if switching to the async configuration when using deferred instead of a sync will fix the behavior but I think it might.
This causes evaluation to break completely under all browsers except Chrome and Firefox. This is a blocker of any new release.
https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages#Browser_compatibility
To avoid 404s when trying to locate a language file, why not implement an index containing the implemented languages? If you just standardise on 'languages.json' under the path, it could be pulled as the first op, parsed and then unimplemented languages could just be skipped.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.