GithubHelp home page GithubHelp logo

coderifous / jquery-localize Goto Github PK

View Code? Open in Web Editor NEW
465.0 24.0 142.0 346 KB

a jQuery plugin that makes it easy to internationalize your web site.

CoffeeScript 10.30% HTML 0.62% CSS 4.61% JavaScript 84.47%

jquery-localize's Issues

Use a language-country localization json file directly.

In some cases, we want the website use a language-country localization json file directly, for example, "zh-CN" (means simplified Chinese) or "zh-TW" (means traditional Chinese).

But the current implementation will first try to load the localization json file with the language code (first two character of the "language" parameter), if it failed, the procedure stops.

For example, if we want to load "message-zh-CN.json", the current implementation will first try to load "message-zh.json", and if it failed, the program stops. This means we must provide an empty "message-zh.json", even if it is useless.

Therefore, the logic of the current implementation should be changed: if the program failed to load the json file with language code, it should continue to try to load the json file with the language-country code.

This issue may have some relation with the issue #22.

chaining on input elements of type submit or reset

Hello,

This library is great and very useful. Many thanks.

I have a little problem using it on such elements, though:

when I chain on several JSON files.

If the entry does not appear in the last JSON file, then the value of the element is set to "", instead of keeping previous value, that would be the expected behaviour (that happened for all other elements, especially for labels).

This generates a problem of compatibility between jquery-localize and jquery-validate, where the use of input elements of such types is proposed.

This problem may be due to my incomplete understanding of the proper way to use this library. If it is the case, please tell me.

Anyway, I have an idea how to find a workaround, by treating localisation for such elements separately.

Many thanks for your patience.

Synchronous XMLHttpRequest

Synchronous XMLHttpRequest on the main thread are being deprecated because of its detrimental effects to the end user's experience. Recent browser versions are deprecating jQuery's async flag. It would be good thing to remove them.

screen shot 2015-07-28 at 12 56 23

two bugs when loading from specific culture (e.g. zh-CN)

  1. line 72: $.parseJSON(xhr.responseText)
    it tries to load xx-zh.json first, but it cannot find it at the first place, so the xhr.responseText will be empty. This causes jquery to throw error and stop.
  2. func: localizeInputElement should have a shortcut for null value
    otherwise, again, in the first try to find xx-zh.json, since it cannot find it, it will set remove existing placeholders and set its value instead.

Localization file fetch stomps global timeout param

Intro: The script uses the getJSON utility function. This fn does not allow you to pass the aync param. The current script does a synchronous fetch using the getJSON function by setting then restoring the global ajaxSettings using the ajaxSetup function.

Problem: If the timeout is undefined prior to the localize call, then, when the previous value is stored away, it is stored as undefined. When you attempt to restore the timeout, since its original value is undefined, it does not reset the timeout back to undefined from the 500ms value that is set by the script - the ajaxSetup function simply calls jQuery.extend which ignores undefined vals. The result is that after executing the localize function, all ajax requests longer than 500ms timeout.

Load 3 data-localize json files

$("[data-localize]")
.localize("header")
.localize("sidebar")
.localize("footer")

The three json files are all loading correct to the browser. I have three json files which look's like this:

  1. header-en.json
    {
    "nav": {
    "assignmentchart": "Belegungsplan"
    }
    }
  2. sidebar-en.json
    {
    "sidebar": {
    "test": "test"
    }
    }
  3. footer-en.json
    {
    "footer": {
    "abc": "testtest"
    }
    }

All three json files should replaced with "data-localize". But only the FIRST!! (header-en.json) file will be replaced. The other HTML Tags with "data-localize" are empty.
What do I am wrong ?

The jquery-localize description says, it should be worked in that order as I think.

best regards.
Chris

Revert back to original translation

Hi,

I've translated my site in English, however, I made a dropdown where people can select a language.
The original language is Dutch in this case.
How can I revert back to Dutch without reloading the page?
Is the only option to create another translation in Dutch in a JSON file?

Thanks in advance!

Setting placeholders to text containing utf-8 Latin1 Supplement chars

We have a problem setting the placeholder of a text input field when the translated text contains non standard chars (for example ü in German translations). I already tried HTML encoding the char(ü) to ü and this works just fine for setting text input values and label values etc. but not for placeholder texts. I use a hidden input control which has the data-localize tag and then after localize function is called I set the placeholder texts by reading this hidden value. But for some reason the placeholder does not seem to decode the encoded text, I also tried setting the ü without encoding but this displays a � char.

Localizing element attributes

Hi,
Instead of deciding which attribute to localize depending on the type of element (i.e. alt and src attributes for image), why don't you add the possibility to assign localized text to any attribute value?
For example:

Problem: localize div title attribute

Possible solution:

The code change for the plugin is easy (in the callback):
var elem, key, value, attr;
elem = $(this);
key = elem.attr("rel").match(/localize[(.?)]/)[1];
attr = elem.attr("rel").match(/attr[(.
?)]/);
value = valueForKey(key, data);
if (attr != null) {
return elem.attr(attr[1], value);
}
else if ...

What do you think?

Yohan

Localize images (src and alt attributes)

I'm using your great plugin on a site that also requires some images to be display in the local language, along with the alternative text.

My quick and dirty implementation based on the existing code is below.

if (elem.is('img')) {
  value = valueForKey(key+'.alt', data);
  if (value) {
    elem.attr("alt", value);
  }
  value = valueForKey(key+'.src', data);
  if (value) {
    elem.attr("src", value);
  }
}

Localized images

I see, inside of plugin code, support for localized images. How work? Thanks :)

Ajax complete

Hello it's possible to re-initialize the localize after a request ajax complete or load event?

example not working

$(document).ajaxStop(function(){
    var opts = { language: "en", pathPrefix: "/" };
    $("[data-localize]").localize("shop", opts);
});

Locales should be 3 characters

Hi! A few languages could have 3 characters as iso code. For example, my language Asturian has 3:

ISO 639-2 "ast" or "ast_ES" in browsers.

Please, could you cover these languages too?

Thanks a lot in advance!

Placeholders.

How to localize placeholders for input elements using Jquery-localize? i can localize the labels , Values of Input element BUT unable to localize the placeholder.

image

OSX / Chrome 44 / US English - language preference not properly detected

  1. Navigate to: chrome://settings/languages
  2. Add 'Spanish' to the list (or any other language)
  3. Drag 'Spanish' to the top
  4. Restart Chrome
  5. Console: navigator.language
    Result: "en-US"

This looks to be an issue w/ how you're detecting the language:
https://github.com/coderifous/jquery-localize/blob/master/src/jquery.localize.coffee#L20

A simple fix to this line would be:

JS

$.defaultLanguage = normaliseLang(navigator.languages? navigator.languages[0] : (navigator.language || navigator.userLanguage));

CS

$.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage)

I'll open a pull-request once I've had a chance to test further!

Getting a simple page to work

Please pardon my ignorance but am having trouble creating a simple page with 5 sets of different languages that changes through the click of a button. I can't find relevant examples in your source.

Thank you.

Localize with jquery 1.9

I use plugin with Jquery 1.9 and have an error at the begining.

In my HTML I have added Jquery, plugin and data-localize
In lang I've added json file
In my JS I've added call
var opts = { pathPrefix: "../lang" };
$("[data-localize]").localize("napo", opts);

When I lanch my app I have this error :
[LOG] Error: SyntaxError: JSON Parse error: Unexpected EOF

I don't know if this problem is link to jquery version, but don't understand this error.
Thanks for your help.

Safari issue, plugin throws an error

Thanks for plugin, it works great for Chrome but we are having some issues for Safari. We are getting this error:

TypeError: $("[data-localize]").localize is not a function. (In '$("[data-localize]").localize("language", opts)', '$("[data-localize]").localize' is undefined)

Any thoughts?

textarea placeholder support

It seems that the placeholder attribute is not supported for textarea 'elements'. Changing one line in the localizElement function fixes the 'issue', since you can use .val(value) on a textarea too:

    localizeElement = function(elem, key, value) {
      if (elem.is('input') || elem.is('textarea')) {
      }
    ...
    }

Local execution of website

Hi.
I use your plugin in an application that can be used locally or hosted in a web server.
I suggest to add an option for local use.
I have modified the code with :

ajaxOptions = {
url: file,
dataType: "json",
/async: false,/
crossDomain: true,
isLocal: true,
timeout: options.timeout != null ? options.timeout : 500,
success: successFunc,
error: errorFunc
};

at the line 71.
Excuse me if I had some mistake with posting suggestion, but it's my first time :)
Have a good day. Alessandra.

File extension as an option to the plugin

Hi,
I've recently had an issue regarding the *.json file extension used for the localization files. My web application (SharePoint 2010) hosting your plugin has an http handler defined for this extension and interferes with the plugin... hence, it doesn't work. I've had no other choice but to recode your plugin to use an optional fileExtension option parameter:
...
loadLanguage = function (pkg, lang, level) {
var file,
fileExt = ".json";
if (options.fileExtension) {
fileExt = options.fileExtension;
}
...

It works fine when I use *.js file extensions. Hopefully, you can include this in your next release! ;)
Thanks,

Yohan

Load files asynchronously and cache them

Synchronous request are now deprecated. Would it be possible to change the ajax request loading the translation files and do it asynchronously?

Then it would be nice to have a cache mechanism to store the translations in memory and thus avoid the asynchronous call if the data was already loaded once.

See warning from Google Chrome:
"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."

Loading external json files

Hello!

First of all, excellent plugin. I'm in a situation with a site where this could be quite useful. However, one problem I ran into was the inability to load cross-domain json files. I tweaked the build file a little bit to accommodate this scenario. I forked the repo before realizing that this was in coffeescript, which I am not familiar with, so I figure I will just post this js code here if you'd like to use it. If I can find some time next week, I'll be happy to take a look at coffeescript and do a proper pull request...

...

$.localize = function(pkg, options) {
var defaultCallback, intermediateLangData, jsonCall, lang, loadLanguage, notifyDelegateLanguageLoaded, regexify, valueForKey, wrappedSet;
if (options == null) {
options = {};
}
options.sameDomain = (typeof options.sameDomain == "undefined") ? true : options.sameDomain;

...

jsonCall = function (file, pkg, lang, level) {

...

ajaxOptions = {
url: file,
dataType: (options.sameDomain) ? "json" : "jsonp",
async: (options.sameDomain) ? false : true,
timeout: options.timeout != null ? options.timeout : 500,
success: successFunc,
jsonpCallback: (options.sameDomain) ? '' : 'successFunc'
};

...

Pretty simple change. Now by adding the option sameDomain: false (default is true) the script will use jsonp instead. I went ahead and specified the callback as the successFunc, since that's what it will wind up passing through anyway. Then all that's left would be formatting your external json file like so:

successFunc({ someString: "some text" });

Anyway, i'm sure others might find this useful. Great plugin and thanks for your work!

Jquery mobile a href and buttons issues

Hello,
thanks for great plugin.

Plugin have some issues if is using with JQM.

For example:

Nastavení

Reset

This:
Reset

should to display button, but with using with rel attr is button deformed.

I tried use other attr's than rel, fxp: i18n but still same result.

I think, that problem should be via Ajax loading of pages in JQM.

I will glad if any fix.

Greeting

Jiri

Default text fallback

Hi.

I am testing out this library and it seems to be perfect for my use. I just have one little problem. When I translate to a language that does not exist, the default values are used instead. But when I translate to a language where a language file exists, but not all the keys, the default value is ignored and a empty value is inserted instead. Is there a way to force the default values to be used instead of an empty string?

Localize parameters

As a developer I would appreciate if the plugin could use parameters so that I don't have to localize any strings with eg. numbers or other constant strings.
In most cases it can be solved by separately localized "span" tags, but in particular cases such as "option" tags you can't. In this case localizing separately each string just because it differs only in the number is waste of space and developers time (not to mention it isn't very elegant).

Example:

Localized JSON
{
my_option: "My option {0}.{1}"
}

HTML:

<select>
<option data-localize="my_option" data-localize-params="1, 1"></option>
<option data-localize="my_option" data-localize-params="1, 2"></option>
<option data-localize="my_option" data-localize-params="2, 1"></option>
<option data-localize="my_option" data-localize-params="2, 2"></option>
<!-- etc. -->
</select>

Result:
Select with options:
My option 1.1
My option 1.2
My option 2.1
My option 2.2

This library does not work on IE or Google

I made a small test and noticed that it only works when run on Firefox on Windows 8.1. When using IE or Crome the library crashes. I cannot even run the test cases you provide but almost all tests fail.

Manually load 'string'

I guess this is more a feature request, but I'll post it here anyway :). I need to localize a web page, but it does not only contain html elements that need translation, there are also some dynamic div's, alerts and prompts. From what I have read it is not possible to do something like loading the localization normally (which localizes all elements on the page) and then after they are loaded use e.g. alert($.localize.load("msg_are_you_sure")) , which will use the last loaded localization. I figured I could use hidden inputs to store all these messages, but the approach I suggested might be more comfortable.

I'm sorry if I overlooked an existing feature here...

problem with multiplie language pack loading

I have this code:
var opts1 = {language: languageValue, pathPrefix: "/webapp/views/utility/resources/langs"};
$("[data-localize]")
.localize("user", opts1)
.localize("member", opts1)
.localize("etcItem", opts1);
});
but just last pack always loaded.files are together and exist.but always last .localize Line load every time.
what is the matter????

fall back logic for zh-xx

"zh-SG", "zh-CN" should fall back to "zh-HANS" (or "zh-CHS")
"zh-TW", "zh-HK", "zh-MO" should fall back to "zh-HANT" (or "zh-CHT")
"zh" is not a valid generic culture.

Loading several language packs does not work

Hello and thank you for such a wonderful plugin.
I tried to integrate your library with my website yesterday and found out that not everything works as it should be...
The code from your documentation:

$("rel*=localize")
.localize("header")
.localize("sidebar")
.localize("footer")

does not work. It throws an exception "the object does not have localize method" when tries to apply localization from the second language pack. I'm using Chrome browser with jQuery 1.5.2.
It would be wonderful if you could fix this issue, thanks!

Force RTL on Arabic and Hebrew

Hello,

How do I make the text to align right to left if the local browser language is Arabic or Hebrew ?

Just for these two languages, I want to html page to use direction:"rtl";

Thanks

Dan

Localize parameters

As a developer I would appreciate if the plugin could use parameters so that I don't have to localize any strings with eg. numbers or other constant strings.
In most cases it can be solved by separately localized "span" tags, but in particular cases such as "option" tags you can't. In this case localizing separately each string just because it differs only in the number is waste of space and developers time (not to mention it isn't very elegant).

Example:

Localized JSON
{
my_option: "My option {0}.{1}"
}

HTML:
...

Script does not localize optgroup tags

My UI uses option groups in drop downs and I would like to be able to localize the labels.

I could do this with a custom callback but I propose that this is a reasonable thing for the default callback to handle. Handling the optgroup would require adding (essentially...) :

    tag = elem.attr('tagName');

           ....

    else if (tag === 'OPTGROUP') {
        elem.attr('label', value);
    }

I think this is a better option than reimplementing the default callback as a custom cb (with the simple addition). The other option would be to scan for the optgroups in a custom cb and "fallthrough" to the default but, this would iterate the wrappedset twice which would not be good.

localize placeholder text

Hello - thanks for the plugin!

Is there a way to use this plugin to localize placeholder text?
For example, I'd like to localize "Please explain" in the following code:

<textarea id="explanation" placeholder="Please explain"></textarea>

Caching JSON

I think the plugin should really be cahing the json file something like this...

var fileCache = {};

jsonCall = function (file, pkg, lang, level) {
            if (!fileCache[lang]) {
                var ajaxOptions, successFunc;
                if (options.pathPrefix != null) {
                    file = "" + options.pathPrefix + "/" + file;
                }
                successFunc = function (d) {
                    $.extend(intermediateLangData, d);
                    notifyDelegateLanguageLoaded(intermediateLangData);
                    return loadLanguage(pkg, lang, level + 1);
                };
                ajaxOptions = {
                    url: file,
                    dataType: "json",
                    async: false,
                    timeout: options.timeout != null ? options.timeout : 500,
                    success: successFunc
                };
                if (window.location.protocol === "file:") {
                    ajaxOptions.error = function (xhr) {
                        return successFunc($.parseJSON(xhr.responseText));
                    };
                }
                fileCache[lang] = $.ajax(ajaxOptions);
            }
                return fileCache[lang];
        };

I dont know coffee otherwise i would submit a pull

AJAX Fallback error when localization file isn't found

Hi,
Why isn't there a fallback error that handles the case where a localization file isn't found? For example, if my locale is set to "en-CA" but I only have a "en" json file, it will try to fetch the "en-CA" file and fail.

Thanks
Yohan

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.