wikimedia / jquery.i18n Goto Github PK
View Code? Open in Web Editor NEW๐ jQuery based internationalization library
License: GNU General Public License v2.0
๐ jQuery based internationalization library
License: GNU General Public License v2.0
I have a message that reads like "{{some template}} some description" and I don't want the parser to try to parse it but I just want it to leave it as is. As far as I wrap my head around the code, this seems not to be possible.
As reported in https://phabricator.wikimedia.org/T95667
It would be great if there were a way to pass message parameters as html5 data attributes.
jQuery.Deferred exception: this.messageStore.load is not a function TypeError: this.messageStore.load is not a function
at I18N.load
Hi,
I am trying to use the package with asp.net application. I loaded the base, messagestore and language js files with jquert 1.10.2. I am vie my application on chrome 49. when my language files are loaded I am getting an error message "Uncaught SyntaxError: Unexpected token :" in the browser console. My language file (en-GB.json) as only one entry { "welcome": "my message" }. Please guide me to resolve this issue
I'm loading messages from two different sources, and it looks like only the messages from the source that is last to arrive actually get picked up.
$.i18n().load( 'a.json', 'en' );
$.i18n().load( 'b.json', 'en' );
Ends up with one of the two messages sets being loaded into the message store, but not the other, and which one makes it is not always consistent (but it's usually b).
The following confirmed my suspicions:
>>> $.i18n().load({'foo':'bar'}, 'en');
Object {resolve: function, resolveWith: function, ...}
>>> $.i18n().messageStore.messages.en
Object {foo: "bar"}
>>> $.i18n().load({'bar':'bar'}, 'en');
Object {resolve: function, resolveWith: function, ...}
>>> $.i18n().messageStore.messages.en
Object {bar: "bar"}
This clearing effect does not happen across languages, only within the same language (so loading messages for 'nl' does not clear messages loaded for 'en', but loading additional messages for 'en' does).
Maybe this was written already, and I missed it...
When a locale is not availble, it looks like the framework will keep requesting the 404-ed file over and over again.
See https://translatewiki.net/wiki/Thread:Support/Too_slow/reply_%286%29 for more details.
Steps to reproduce:
Observe the loaded URLs in Firebug or whatever dev tool you're using.
Hello,
It would be useful to have a Bower package for this library.
Regards,
When I chose with uparrow key or downarrow key, the lang josn will be load twice in the DEMO.
I'm from China, my English is poor, thank you.
Currently the json files are loaded directly from the server. At translatewiki.net I have configured 30 minute caching time for them. This however means that if new messages are introduced, ULS will display placeholders until the file is recached client side. Nginx doesn't do etags, so another solution would be most welcome (at simplest appending ULS version string to the url of loaded files).
Hi:
When i click tab to switch to another page, the tag data-i18n = XXX will fail and must call $ ('body'). I18n (); How can i18n automatically listen and refresh dom?
I don't know how to solve this problem: How would you use the transparent technique, $('[data-i18n]').i18n(), to localize an element attribute such as <input value="msgname" ,,, ?
Say I want to replace just the Exit
text for an HTML button
,
<button data-i18n="Exit">Exit
<i class="sign out icon"></i>
</button>
If I do $('[data-i18n]').i18n()
the inner i
HTML element is lost,
<button data-i18n="Exit">Exit</button>
I'm afraid this is not an issue, but I couldn't find how to do it properly.
Thanks in advance.-
Hi Guys,
I see that there are two LICENSE files in the repository: GPL and MIT. Which is correct?
And from my knowledge (may be wrong) you cannot have both, as GPL is in conflict with MIT.
Thanks for clarification!
EDIT: minutes after posting i found out I need to do
// on a sidenode, the test "jquery.i18n: Message load tests (1, 13, 14)" in my browser gives me a failed test on each rerun (on first run the test passes)
forget below.
Using jquery.i18n for the first time, I expected jquery.i18n to be working in the way i have set up in the third test-case. (i tought i wouldn't need to keep a reference to the instance of i18n i created.)
In short, my intention was to load all language-resources on pageload, then on user-request changing the locale and calling $("*").i18n(); to have every data-i18n tag like <div data-i18n=demo></div>
translated.
Can anyone confirm the way i18n is intended to be used is by keeping a reference myself, or is this a bug in the library?
See the 3 testcases below for more info
`
( function ( $ ) {
'use strict';
QUnit.module( 'jquery.i18n - is this a bug?', {
setup: function () {
$.i18n( {
locale: 'localex'
} );
},
teardown: function () {
$.i18n().destroy();
}
} );
QUnit.test( 'WORKS: switch locale using $( document ).data( "i18n" ) instance', 4, function ( assert ) {
$.i18n.locale = "localeinitial";
// Load messages for two locales - nl , fr
$.i18n().load( {
nl: { one: 'nl-ONE' },
fr: { one: 'fr-ONE' }
} );
var $elem = $("<li data-i18n=one>initial text</li>");
// Switch to locale nl
$( document ).data( 'i18n' ).locale = 'nl';
assert.strictEqual( $( document ).data( 'i18n' ).locale, 'nl', 'Locale switched to nl' );
$elem.i18n();
assert.strictEqual($elem.text(), 'nl-ONE', 'first translation');
$( document ).data( 'i18n' ).locale = 'fr';
assert.strictEqual( $( document ).data( 'i18n' ).locale, 'fr', 'Switch Locale to fr' );
$elem.i18n();
assert.strictEqual($elem.text(), 'fr-ONE', 'second translation');
} );
QUnit.test( 'WORKS: switch locale holding the instance', 4, function ( assert ) {
var i18n = $.i18n();
//$.i18n();
//var i18n = $( document ).data( 'i18n' );
i18n.locale = "localeinitial";
// Load messages for two locales - nl , fr
i18n.load( {
nl: { one: 'nl-ONE' },
fr: { one: 'fr-ONE' }
} );
var $elem = $("<li data-i18n=one>initial text</li>");
//assert.strictEqual($elem.text(), 'initial text', 'assertion of initial text works');
// Switch to locale localey
i18n.locale = 'nl';
assert.strictEqual( i18n.locale, 'nl', 'Locale switched to nl' );
$elem.i18n();
assert.strictEqual($elem.text(), 'nl-ONE', 'first translation');
i18n.locale = 'fr';
assert.strictEqual( i18n.locale, 'fr', 'Switch Locale to fr' );
$elem.i18n();
assert.strictEqual($elem.text(), 'fr-ONE', 'second translation');
} );
QUnit.test( 'FAILS: switch locale using $.i18n', 4, function ( assert ) {
$.i18n.locale = "localeinitial";
// Load messages for two locales - nl , fr
$.i18n().load( {
nl: { one: 'nl-ONE' },
fr: { one: 'fr-ONE' }
} );
var $elem = $("<li data-i18n=one>initial text</li>");
// Switch to locale localey
$.i18n.locale = 'nl';
assert.strictEqual( $.i18n.locale, 'nl', 'Locale switched to nl' );
$elem.i18n();
assert.strictEqual($elem.text(), 'nl-ONE', 'first translation');
$.i18n.locale = 'fr';
assert.strictEqual( $.i18n.locale, 'fr', 'Switch Locale to fr' );
$elem.i18n();
assert.strictEqual($elem.text(), 'fr-ONE', 'second translation');
} );
}( jQuery ) );
`
Hello, the document mentions CLDR plurals but does not show how they map to messages. It might be helpful to show that for English the form is {{PLURAL:$1|one|other}}
, for Arabic {{PLURAL:$1|zero|one|two|few|many|other}}
etc. Since the format does not have the keyword names in the text, it was particularly confusing at first that the keywords are skipped if not found in the language (so for example zero
is omitted from English).
Thanks!
On your github home page https://github.com/wikimedia/jquery.i18n, the license link states that jquery.i18n uses GPL-2.0 which we cannot use in our product. However if you click on the GPL icon, it takes you to a page where it says MIT license, which we can use in our product. https://github.com/wikimedia/jquery.i18n/blob/master/MIT-LICENSE. Can you tell me which license jquery.i18n is using?
I followed documentation about file format. So I've supplied i18n/fr.json
as follow :
{
"@metadata": {
"authors": [
"Mathieu BODIN"
],
"last-updated": "2014-07-23",
"locale": "fr",
"message-documentation": "qqq"
},
"fr": {
"something": "qqchose"
}
}
I've loaded that file somewhere like that :
$.i18n().load("i18n/fr.json","fr")
Then I tried to use it, like that :
var label = $.i18n("something");
It just NEVER happened to work until, after reading the code of the example, I tried the following content for i18n/fr.json
file:
{
"something": "qqchose"
}
So my question is : why didn't it work at first with message source formatted as documented ?
By the way, what's the point of:
In the README is documented how to create a single message file containing multiple locales.
How do I load this message file dynamically via the $.i18n().load()
method?
This is not documented in the README section about message loading.
Looks like the upgrades to 30 only just happened... But worth checking over and updating further as appropriate
I've got some translations with html markup (specifically ). Due to varying word order, I would like to somehow keep the ability to add these tags in the translation files. Something like this:
http://stackoverflow.com/questions/16038458/html-tags-in-i18next-translation
I have tried both directly inputing the HTML directly into the JSON data and creating my own magic word to no avail. In both cases the raw html shows up. Is it possible to use HTML tags in the translations?
Can I use i18n for DOM attrs like title or placeholder without using JS to change it's attribute? for example:
<div class="content">
<input type="text" placeholder="translate me" title="translate me">
</div>
How can I use:
$('div.content').i18n();
To update the translated messages for placeholder or title?
Make it upto date with https://gerrit.wikimedia.org/r/#/c/49615
Hello:
Can I use nested locale structure? For example, change the following:
{
"@metadata": {
"authors": [
"Developer Name"
]
},
"appname-title": "Application name. Transliteration is recommended",
"appname-sub-title": "Brief explanation of the application",
"appname-header-introduction": "Text for the introduction header",
"appname-about": "About this application text",
"appname-footer": "Footer text"
}
to:
{
"@metadata": {
"authors": [
"Developer Name"
]
},
"appname":{
"title": "Application name. Transliteration is recommended",
"sub-title": "Brief explanation of the application",
"header-introduction": "Text for the introduction header",
"about": "About this application text",
"ooter": "Footer text"
}
}
Thanks a lot!
I understand that this request may seem unreasonable for a library with "jquery" in its name, but some components like the parser would be amazingly useful for server-side apps.
Apparently there are pluralization issues for language codes bs, hr and sr.
Bosnian for instance:
Message: "num-languages": "$1 {{PLURAL:$1|jezik|jezika}}"
In the JavaScript console:
$.i18n('num-languages', 115);
=> "115 jezik"
When it should be 115 jezika
.
If you need a go-to for Bosnian, @srdjanm has offered to help. They said the plural rules look correct, so maybe it's something else.
Thanks!
Hello,
could you please help me how to load my json resource file with key/value strings pairs ?
This is how I load my json source file. I used ASP.NET MVC classical folder hierarchy (View, Controllers, Scripts) where should I add this file ? If I place it into e.g. /Scripts should be my path = "~/Scripts/MyFolder/en.json" ? I could not load json file. And I try to access to my string resource like
Or Am I doing something wrong ?
Thx
Lukas
This bears some relation to #18
It should be possible to specify a URL to a directory that contains files of the form LANGCODE.json, and have jquery.i18n automatically fetch the .json file for the current language and its fallbacks.
The former is something that a caller can fairly easily emulate by doing something like
To avoid confusions.
When a message-key is defined in the JSON file, but intentionally left blank then the message should not fallback to another language.
Check should be typeof message === 'string' instead
https://github.com/wikimedia/jquery.i18n/blob/master/src/jquery.i18n.js#L67
I have a message containing and HTML element like "test
text", but my "br" is displayed as escaped element. How to avoid elements escaping? I'm using the transparent $('[data-i18n]').i18n(); technique to translate all the content in my single page app.
In the absence of a "dist" folder, it seems safe to assume that the contents of the "src" file (the JavaScript files) are the distributables that should be included on a page.
Looking at the source code of the example seems to support this, with the following files being included:
<script src="../src/jquery.i18n.js"></script>
<script src="../src/jquery.i18n.messagestore.js"></script>
<script src="../src/jquery.i18n.fallbacks.js"></script>
<script src="../src/jquery.i18n.parser.js"></script>
<script src="../src/jquery.i18n.emitter.js"></script>
<script src="../src/jquery.i18n.language.js"></script>
Followed by a few specific language files. It wasn't until I looked at the contents of the language files that I understood that they are extensions for formatting.
Also, higher up in the sample page, I see that the CLDR parser is included. I imagine that it is a requirement?
If my build script concatenates the following into one file, am I meeting the requirements for what is needed on the page (for the browser) in order to use i18n? I am just using the sample page's paths here; I would provide my own paths within the Grunt or Gulp:
../libs/CLDRPluralRuleParser/src/CLDRPluralRuleParser.js
../src/jquery.i18n.js
../src/jquery.i18n.messagestore.js
../src/jquery.i18n.fallbacks.js
../src/jquery.i18n.parser.js
../src/jquery.i18n.emitter.js
../src/jquery.i18n.language.js
And then language-specific functions and the emitter.bidi.js if needed?
Although I think my inferences are correct here, the documentation could be improved with a clear section on what needs to be included in order to have a functioning instance of i18n.
Also: the latest zip doesn't seem to include the CDLRPluralRuleParser that's being referenced. I imagine it can be had from CLDR's own repository, but I don't believe that it's documented anywhere. It seems to be assumed that the JavaScript file would appear in that directory.
I want to define my JSON file location from script. Maybe like this:
$.i18n( {
locale: "../an.app/locale/en.json"
} );
Is it possible?
in language.js, near "// default fallback."
Shouldn't the fallback exclude what's left of the equal sign?
var fallback = ( count === 1 ) ? forms[0] : forms[1];
fallback = fallback.substr( fallback.indexOf( '=' ) + 1 );
return fallback;
In a normal, non-MediaWiki page in Chrome, I get:
>>> $.i18n().locale
"en-US"
>>> promise = $.i18n().load({'foobar':'Wheeee!'}, $.i18n().locale)
Object
>>> promise.state()
"resolved"
>>> $.i18n('foobar')
"foobar"
It looks like the default locale in Chrome is en-US and this is breaking jQuery.i18n. I can't set arbitrary messages into en-US and then read them back out.
This does work in a MediaWiki context because of , but this makes jQuery.i18n unusable in non-MediaWiki contexts.
Hi
First of all great job, very nice and useful plugin!
In my application I using Grunt with grunt uglify.
All looks good, but on load I got a lot of ajax error on cosole.
After deep investigation I found that inside function load in for in loop it takes Array.prototype functions and pushes them inside ajax load urls:
On debug mode you can see that array length is 1, but the code continue to take prototype function:
The result is many errors in console of ajax failed requests:
I around the array prototype functions on the PS.
I found that if I replace for in to array.foreach this problem is not happend
// for ( locIndex in fallbackLocales ) {
// fallbackLocale = fallbackLocales[locIndex];
// sourceMap[fallbackLocale] = source + '/' + fallbackLocale + '.json';
// }
fallbackLocales.forEach(function(locale) {
sourceMap[fallbackLocale] = source + '/' + locale + '.json';
});
For your review
Friends library has support for objects inside objects because my script is criticizing:
Uncaught TypeError: message.indexOf is not a function
example json:
{
"en": {
"appname-title": "Example Application",
"appname-sub-title": "An example application with jquery.i18n",
"appname-header-introduction": "Introduction",
"example": {
"appname-title": "Example Application",
"appname-sub-title": "An example application with jquery.i18n"
},
"appname-about": "About this application",
"appname-footer": "Footer text"
},
"ml": {
"appname-title": "เด
เดชเตเดฒเดฟเดเตเดเตเดทเดจเตโ เดเดฆเดพเดนเดฐเดฃเด",
"appname-sub-title": "jquery.i18n เดเดชเดฏเตเดเดฟเดเตเดเตเดณเตเดณ เด
เดชเตเดฒเดฟเดเตเดเตเดทเดจเตโ เดเดฆเดพเดนเดฐเดฃเด",
"appname-header-introduction": "เดเดฎเตเดเด",
"example": {
"appname-title": "Example Application",
"appname-sub-title": "An example application with jquery.i18n"
},
"appname-about": "เด เด
เดชเตเดฒเดฟเดเตเดเตเดทเดจเตเดชเตเดชเดฑเตเดฑเดฟ",
"appname-footer": "เด
เดเดฟเดเตเดเตเดฑเดฟเดชเตเดชเตเต"
}
}
}
```
The fallbacks are all defined in lowercase, but a lot of browsers report the locale with uppercase region. For example, the browser is reporting zh-TW
, which should fall back to zh-hant
. However, because it doesn't match zh-tw
in the fallbacks file, it uses en
instead.
The standard as far as I know is that the tags should be case insensitive (https://tools.ietf.org/html/bcp47), so it should correctly fall back regardless of the input case.
For now, I'm just forcing the locale to lowercase, which resolves this issue, but it should probably be fixed in the library itself.
The textContent of DOM element is changed to message-key in case there is no translation defined. In the doc it is claimed the original text will be used as fallback.
See sample:
https://jsfiddle.net/ajbmkwbr/
In Firefox $.i18n.load() does not work.
I fixed it in this way:
In jquery.i18n.messagestore.js substitute
function jsonMessageLoader( url ) {
var deferred = $.Deferred();
$.ajax({
dataType: "json",
url: url,
contentType:'text/plain',
mimeType: "text/plain",
dataType: 'text',
success: success
})
.done( deferred.resolve )
.fail( function ( jqxhr, settings, exception ) {
$.i18n.log( 'Error in loading messages from ' + url + ' Exception: ' + exception );
// Ignore 404 exception, because we are handling fallabacks explicitly
deferred.resolve();
} );
return deferred.promise();
}
Hi,
It looks like the plural rules for Russian need to be updated. If I'm reading this correctly, the current version in this repository only has one/many rules, whereas CLDRPluralRuleParser, even at the version on this repository, has a few more. This causes the wrong plural to be chosen sometimes (specifically, I've seen it happen for the "few" case).
(This may be related to #26 or #125, but the former is old and a bit cryptic, and the latter mentions that the plural rules are correct, so I figured I'd file something separate, feel free to duplicate).
Is it possible to use something like
$( document ).on( "language-change", function() {
console.log( "Language just changed." );
});
to detect language change so that I can make corresponding changes to the interface's UI? Thanks! :)
$
immediately followed by any characters will cause an error when used in a json array. The error is Uncaught TypeError: Cannot read property '2' of undefined in simpleParse js file.
$1, $2, $3 are placeholders for the library so it seems $4500
causes an error whereas $ 4500
doesn't cause any issues. Replacing$
with $
doesn't solve the issue.
How does one escape $
in a message then?
mediawiki.org documentation and jquery.i18n README don't specify in what cases jquery.i18n is preferred/needed over jqueryMsg (reported by @ebernhardson).
I'm adding a link on https://www.mediawiki.org/w/index.php?title=Manual:Messages_API&diff=1064527&oldid=1057080 but at least the README here should clarify the difference. Ideally we'd also have a one-line explanation of the difference, which could then be usable on [[Manual:Messages API]] with appropriate prominence.
With fa
set as the language, the Langviews tool tried to translate a particular message that is not defined in fa.json, so it falls back to English. The English message uses {{PLURAL}}, which errors out presumably because the rules differ than what is defined for fa
. E.g. if I removed the rules for fa
here then I get no error. I am seeing the same issue for some other RTL languages.
Console shows pluralRuleParser
is undefined here.
If I'm understanding this correctly, I think we just need to resort to the en
defined rules when falling back to an English message.
Could you tag v0.1.0
at 2837060? (Creates package.json which first mentioned that number afaics.)
Also a more recent tag would be nice so end users can link to a less random point of master for their downstream copies (maybe tag current master at v0.2.0
or something?).
Lastly, a versioning section in the readme would be nice to make sure there's a somewhat defined path for maintainers to follow and users of the code to expect (not important until it goes 1.x but good to put in place ahead of time).
Something like https://github.com/wikimedia/oojs#versioning or https://github.com/twbs/bootstrap#versioning (if you like Semantic Versioning).
Love this project - just have one issue...I have the following code where i call initResources() as soon as the document ready fires. I have a race condition in that other js code executes before the load() completes and I cannot get the string resource. How can I block/wait for the load to complete before trying to access the string resources in a safe way?
that.getResource = function(key, param1) {
if (!localeInitialized) {
that.log('resource not loaded!');
}
return $.i18n(key, param1);
},
that.initResources = function() {
i18N = $.i18n();
i18N.locale = $('html').attr('lang');
i18N.load('/scripts/lang/' + i18N.locale + '.json', i18N.locale).done(function () {
localeInitialized = true;
});
},
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.