Giter VIP home page Giter VIP logo

i18next / jquery-i18next Goto Github PK

View Code? Open in Web Editor NEW
167.0 12.0 86.0 3.59 MB

jQuery-i18next is a jQuery based Javascript internationalization library on top of i18next. It helps you to easily internationalize your web applications.

Home Page: https://locize.com/blog/jquery-i18next/

License: MIT License

JavaScript 34.62% HTML 54.73% CSS 10.65%
jquery i18next i18n translation internationalization jquery-plugin javascript jquery-i18n

jquery-i18next's Introduction

Introduction

Source can be loaded via npm, bower or downloaded from this repo or from a CDN like CDNJS.


NEWS: localization as a service - locize.com

Needing a translation management? Want to edit your translations with an InContext Editor? Use the orginal provided to you by the maintainers of i18next!

locize

With using locize you directly support the future of i18next and react-i18next.


Advice:

To see jquery-i18next in a working app example, check out this blog post and this example.


If you don't use a module loader it will be added to window.jqueryI18next

# npm package
$ npm install jquery-i18next

# bower
$ bower install jquery-i18next

Simplifies i18next usage in projects built based on jquery, like:

page source:

<ul class="nav">
  <li><a href="#" data-i18n="nav.home"></a></li>
  <li><a href="#" data-i18n="nav.page1"></a></li>
  <li><a href="#" data-i18n="nav.page2"></a></li>
</ul>

loaded resource file (locales/en/translation.json):

{
  "nav": {
    "home": "Home",
    "page1": "Page One",
    "page2": "Page Two"
  }
}

javascript code:

$(".nav").localize();

// results in
// <ul class="nav">
//  <li><a href="#" data-i18n="nav.home">Home</a></li>
//  <li><a href="#" data-i18n="nav.page1">Page One</a></li>
//  <li><a href="#" data-i18n="nav.page2">Page Two</a></li>
// </ul>

Initialize the plugin

jqueryI18next.init(i18nextInstance, $, {
  tName: 't', // --> appends $.t = i18next.t
  i18nName: 'i18n', // --> appends $.i18n = i18next
  handleName: 'localize', // --> appends $(selector).localize(opts);
  selectorAttr: 'data-i18n', // selector for translating elements
  targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if different than itself)
  optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
  useOptionsAttr: false, // see optionsAttr
  parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
});

using options in translation function

<a id="btn1" href="#" data-i18n="myKey"></a>
$("#btn1").localize(options);

or

<a id="btn1" href="#" data-i18n="myKey" data-i18n-options='{ "a": "b" }'></a>
$("#btn1").localize();
// make sure you set the useOptionsAttr option to true if you want to pass the i18n options via data-i18n-options attribute.

data-i18n-options attribute must be a valid JSON object.

usage of selector function

translate an element

<a id="btn1" href="#" data-i18n="myKey"></a>
$("#btn1").localize(options);

myKey: same key as used in i18next (optionally with namespaces) options: same options as supported in i18next.t

translate children of an element

<ul class="nav">
  <li><a href="#" data-i18n="nav.home"></a></li>
  <li><a href="#" data-i18n="nav.page1"></a></li>
  <li><a href="#" data-i18n="nav.page2"></a></li>
</ul>
$(".nav").localize();

translate some inner element

<div class="outer" data-i18n="ns:key" data-i18n-target=".inner">
  <input class="inner" type="text"></input>
</div>
$(".outer").localize();

set different attribute

<a id="btn1" href="#" data-i18n="[title]key.for.title"></a>
$("#btn1").localize();

set multiple attributes

<a id="btn1" href="#" data-i18n="[title]key.for.title;myNamespace:key.for.text"></a>
$("#btn1").localize();

set innerHtml attributes

<a id="btn1" href="#" data-i18n="[html]key.for.title"></a>
$("#btn1").localize();

prepend content

<a id="btn1" href="#" data-i18n="[prepend]key.for.title">insert before me, please!</a>
$("#btn1").localize();

append content

<a id="btn1" href="#" data-i18n="[append]key.for.title">append after me, please!</a>
$("#btn1").localize();

set data

<a id="btn1" href="#" data-i18n="[data-someDataAttribute]key.for.content"></a>
$("#btn1").localize();

Gold Sponsors

jquery-i18next's People

Contributors

adrai avatar dreadknight avatar eiurur avatar jamuhl avatar jgobi avatar luanreis avatar peterjosling avatar vdemin avatar vsa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-i18next's Issues

Error message i18nextJquery.init is not a function

I did bower install i18next/i18next-jquery.
Then tried to access it from my applications app.js
let i18nextInstance = i18next.createInstance();
i18nextJquery.init(i18nextInstance, $);

//here i18nextJquery is my AMD module name which is pointing to i18nextJquery/i18next-jquery.min.js

But I am getting error from require.js
"Uncaught TypeError: i18nextJquery.init is not a function"

Am I missing something?

localize not defined when .use(i18nextBrowserLanguageDetector) is called

Hi,

I have upgraded my i18next from 1.11.1 to 8.4.3 and use the following plugins. It kept telling me localize is not defined. What should I do?

  1. i18nextXHRBackend
  2. i18nextBrowserLanguageDetector
  3. jqueryI18next

My init routine:

    i18next
        .use(i18nextXHRBackend)
        .use(i18nextBrowserLanguageDetector)
        .init({
            fallbackLng: 'en',
            debug: true,
            backend: {
                // load from i18next-gitbook repo
                loadPath: './locales/{{lng}}/translation.json',
                crossDomain: true
            }
        }, function(err, t) {
            // for options see
            // https://github.com/i18next/jquery-i18next#initialize-the-plugin
            jqueryI18next.init(i18next, $, {
            	handleName: "localize",
            	selectorAttr: "data-i18n"
            });
            // start localizing, details:
            // https://github.com/i18next/jquery-i18next#usage-of-selector-function
            updateContent();
        });

    function updateContent() {
        $('title').localize();
        $('[data-i18n]').localize();
    }

console warning in firefox

Hello
(on Mac 10.11.3, latest firefox) when using firefox I got the following warning

mutating the [[Prototype]] of an object will cause your code to run very slowly; instead create the object with the correct initial [[Prototype]] value using Object.create

i18next.min.js

This does not appear when running on Chrome.

HTML from options attribute is appended as text regardless of the [html] prefix

When I was using version of 1.x of i18next i had this kind of element on my site:

<p data-i18n="[html]agreeTos" data-i18n-options='{"tosLink":"<a href=\"#\" target=\"_blank\">$t(agreeTosLinkText)</a>"}'></p>

and it translated the text with clickable link at the end. But in current version of the plugin this thing is broken. I get the link rendered as plain text, not the actual link. I am not sure what changed and if I am still doing it correctly, so i would appreciate any help in this matter. Thanks.

complex replacement i18n vs i18next

I am evaluating the differences and ease of use between jQuery i18n and i18next, and it seems that it is much less work in certain cases to translate using i18n, but perhaps I am missing something. For example, how would I write this i18n phrase:

var phrase = $1 has $2 {{plural:$2|kitten|kittens}}. {{gender:$3|He|She}} loves to play with {{plural:$2|it|them}}.

$.i18n( phrase, 'john', 2, 'male');

in i18next? What is good about this way of writing (i18n) is that the context and entire sentence is clear, but I am not sure at all how I would achieve the same contextual clarity using i18next in a single translated line with 3 variables (1 normal variable, one plural, and one gender). Can you tell me how I might achieve the same using i18next syntax?

Load i18next on framework7 ajax loaded pages

I am using i18next jquery version to localize the text. It works on each file if I click the button to change language (using localstorage to save the language option). But If I load another file in the view for example about page, it doesn't work.

Here is my i18next function with translation (language.js):

var itemslang = {
    "en": {
        "translation": {
          /* MENU */
          "About-Framework7": "About-Framework7",
          "Welcome-to-Framework7": "Welcome-to-Framework7",
        }
    },
        "br": {
        "translation": {
          /* MENU */
          "About-Framework7": "Sobre o Framework7",
          "Welcome-to-Framework7": "Bem Vindo ao Framework7",
        }
    }
};

$(document).ready(function() {
    var language = "en";
    if (localStorage.getItem("language") != null)
        language = localStorage.getItem("language");

    i18n.init({
        lng: language,
        resStore: itemslang,
        fallbackLng: "en"
    }, function(o) {
        $(document).i18n()
    }), $(".lang").click(function() {
        var o = $(this).attr("data-lang");

        localStorage.setItem("language", o);

        i18n.init({
            lng: o
        }, function(o) {
            $(document).i18n()
        })
    })
});

Can anyone point me on how to apply the translation on all pages and not just the first?

When there is no default value when binding to an attribute it inserts the key instead of blank

Say you have the HTML:
<input type="text" data-i18l="[title]namespace.key.to.use" />

Now say you have a default of en-GB which does not have a value for that namespace/key and you initialise i18l to use German version of resources (de) which does have the namespace/key.

When you view the page with German language, all is well and you get a text input displayed and when you hover over it you get a tooltip as specified in the title attribute that you localize() with.

The bug happens when you switch to the English language (in this example). Because it does not have the above namespace/key when you hover over the text input displayed on the page you get a tooltip that says "namespace.key.to.use".

I can't see when this behaviour would be useful in the instance where the key doesn't exist it should just add the title attribute with no content not use the key as the text. This is what it does in other cases, e.g. if you have <h2 data-i18l="namespace.page.title"></h2>, and the key doesn't exist you'd end up with an empty <h2> tag not <h2 data-i18l="namespace.page.title">namespace.page.title</h2>

Cannot read property 'parseDefaultValueFromContent' of undefined

Hi. Like the title says, I am still getting this error in the console. I am using i18next version 2.0.22 with jquery-i18next version 0.0.10 and my setup looks like this:

var i18options = {
    lng: 'en',
    fallbackLng: 'en',
    backend: {
        loadPath: 'locales/{{ lng }}.json'
    }
};

i18next
    .use(i18nextXHRBackend)
    .init(i18options, function(err, t) {

        i18nextJquery.init(i18next, $, {
            useOptionsAttr: true,
            parseDefaultValueFromContent: true
        });

        $('body').localize();

    });

When i set useOptionsAttr to false the issue is gone, but I need this option so that does not solves my problem. Is this coused by some bug in the plugin or maybe I am doing something wrong? Here is how i try to translate some element one the page:

<div data-i18n="[html]fileSize" data-i18n-options='{ "size": "110 KB" }'>File size: <strong>110 KB</strong></div>

en.json

{
  "fileSize": "File size: <strong>__size__</strong>"
}

Thanks for the help! :)

TypeError: i18nextJquery.init is not a function.

Hello,
I have downloaded the zip from the repository, and added i18next-jquery.min.js to my page,
It gives me that error message:
TypeError: i18nextJquery.init is not a function. (In 'i18nextJquery.init', 'i18nextJquery.init' is undefined)

I tried with the example in the repository, if I replace the cdnjs address by the local i18next-jquery.min.js
I have the same error.

my code works also works if I call the cdnjs version instead of the local one
any idea ?

thanks

Strings with ":" character inside will not be translated client-side

Hi.
I was trying your jquery-i18next module and I noticed that if a string contains the character ":", the translation will not be made. When we activate the debug option, we can see in the console log that it tries to translate the string without the ":" character. And because in the json resource file the string contains the ":" character, i18next don't find the translation for that string.

For example, if I have this line:

<title class="MyTest" data-i18n="Yeeahh: My First Translated Web Page"></title>

jquery-i18next will try to translate "Yeeahh My First Translated Web Page" (without the ":" character) instead of "Yeeahh: My First Translated Web Page" (with the ":" character)

(or maybe it tries to translate only the string in the right-side of the ":" character: "My First Translated Web Page" )

Here is what we can find in the json resource file (for french language for example)

{
    "Yeaahh: My First Translated Web Page": "Yeaahh: Ma première page web traduite",
    "Choose your favorite application:": "Choisissez votre application favorite:"
}

And Here is my web page (HTML):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US">
    <head>
      <script type="text/javascript" src="lib/i18next.js"></script>
      <script type="text/javascript" src="lib/i18nextXHRBackend.js"></script>
      <script type="text/javascript" src="lib/i18nextBrowserLanguageDetector.js"></script>
      <script type="text/javascript" src="lib/jquery.min.js"></script>
      <script type="text/javascript" src="lib/jquery-i18next.min.js"></script>

      <script type="text/javascript">
        var i18nextOptions = {
                              load:['en-US', 'fr', 'es'],
                              whitelist:['en-US', 'fr', 'es'],
                              fallbackLng: 'en-US',
                              ns:'Web_Server',
                              defaultNS:'Web_Server',
                              backend: {loadPath: '/language/static/{{lng}}/{{ns}}.json', addPath: 'language/static/add/{{lng}}/{{ns}}.json'},
                              detection: {order: ['querystring', 'cookie', 'navigator', 'localStorage'],
                                          lookupQuerystring: 'lng',
                                          lookupCookie: 'i18next',
                                          lookupLocalStorage: 'i18nextLng',
                                          caches: ['localStorage', 'cookie'],
                                          cookieMinutes: 5},
                              debug: true
                             };
        i18next
          .use(i18nextXHRBackend)
          .use(i18nextBrowserLanguageDetector)
          .init(i18nextOptions, function(err, t){

            jqueryI18next.init(i18next, $);

            $('.MyTest').localize();
          });

      </script>

      <meta http-equiv="Content-Type" content="text/html; charset=utf8" />
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">

      <title class="MyTest" data-i18n="Yeaahh: My First Translated Web Page"></title>
      <link rel="stylesheet" href="lib/bootstrap-3.1.1/css/bootstrap.min.css">
      <link rel="stylesheet" href="lib/bootstrap-3.1.1/css/bootstrap-theme.min.css">
      <link rel="stylesheet" href="css/style.css"/>

    </head>

And Finally, this is what we can see in the console log:

i18next::backendConnector: loaded namespace My_Web_Server for language fr Object
i18next.js:111 i18next::backendConnector: loaded namespace My_Web_Server for language en-US Object
i18next: languageChanged fr
i18next: initialized Object {debug: true, ns: Array[1], defaultNS: "My_Web_Server", fallbackLng: Array[1], fallbackNS: false…}
i18next::translator: missingKey fr Yeeahh  My First Translated Web Page  My First Translated Web Page
i18next::translator: missingKey fr Choose your favorite application        

For the string "Yeeahh: My First Translated Web Page", in the console log, I don't know if it's an error from the module, but the log looks a little bit weird:

i18next::translator: missingKey fr Yeeahh My First Translated Web Page My First Translated Web Page

You can see that "My First Translated Web Page" is repeated twice. It's not so bad but for the eyes, you know... ;-)

Thank you in advance for your answer :-)

Error: "Invalid left-hand side in assignment"

In the file jquery-i18next.js in line 4 you wrote:
global.jquery-i18next = factory()
there i get an error: "Uncaught ReferenceError: Invalid left-hand side in assignment(…)"
i think the a name with "-" is not working
i tried to fix it locally like that: global['jquery-i18next'] = factory()
-> it works again

Thanks

Issue with [prepend] and [append] attributes

Hi @jamuhl ,

I noticed that there is an issue with prepend and append attributes. Each and every time the language is switched it is prepending or appending the same content again and again.

For ex:
<div data-i18n="[prepend]information"> is wealth.</div>

Suppose if my app is supporting 2 languages English and German then each time I change the language it is prepending the same text in the chosen language each time I change the language.

Actual Output (Switched the language from English to German 4 times):
GE - Information. Information GE - Information. Information GE - Information is Wealth

Expected Output:

GE - Information is Wealth. (If language chosen is German)
Information is Wealth. (If language chosen is German)

I actually took a look at the source code and for prepend and append in jquery-i18next.js line no: 67 and I found that it doesn't have any intelligence of finding the already prepended/appended element and then just localize it but instead each time it actually prepends or appends to the element content which is actually causing the issue.

How can Key Fallback option be used for translations

Hi,
I have started plying with language translation with i18next. Thanks a lot for this, it works too good for my pages. I'm able to use postprocessing also with sprintf and play around with multiple name spaces.
I wanted to use key fallback(not language fallback) with my translations.
my content goes like below.

//locales/en/translation.json
{
"listView": {
"flight": "FLIGHT",
"tow": "TOW",
"freeTxt": "FREE TEXT",
"estp": "E-STOP",
"newFltPln": "New Flight Plan",
"aircftTyp": "Aircraft Type",
"callSign": "Call Sign",
"buttonName": "Save Data"
"errMsg": "Can't Translate"
}
}

//initialization goes something like this
i18next
.use(i18nextXHRBackend)
.init({
lng: en,
fallbackLng: ['de', 'en'],
debug: true,
ns: ['translation'],
backend: {
loadPath: '../../../locales/{{lng}}/{{ns}}.json',
crossDomain: true
}
}, function(err, t) {
jqueryI18next.init(i18next, $);
$(.listView).localize();
});

my requirement is , if I want to pass a fallback key(e.g errMsg) along with translation key like i found as below in documentation, how should I pass it?

i18next.t([error.${error}, 'error.unspecific'])

Thank you for your time.
Regards,
Chandra

Replace HTML tags tokens from translation

🚀 Feature Proposal

Implement Trans react component functionality for jquery

Let's assume that in translation I do have text like:
"userMessagesUnread": "Hello <1>{{name}}</1>, you have {{count}} unread message."

It would be nice if on client side code I can define by myself what kind of HTML tags I want to use for <1></1>
So, usage will be:

<p data-i18n="userMessagesUnread">
  Hello <strong>{{name}}</strong>, you have {{count}} unread message
</p>

Motivation

Using separation of concerns principle we don't need to store HTML tags directly in translations

upgrading from v1

hello,
I have been using the previous version which called the translations as $.t('key.value')

I am completely at lost as how do I change these.
do I understand well that if I was using

$.t('key.value') I must use ?

giving all headers (or the top div ?) a class and the $(.myclass).localize();

I use jQuery.validation and I have additional methods:
$.validator.addMethod('le', function(value, element, param) {
return this.optional(element) || parseInt(value) <= parseInt($(param).val())
},$.t('invalid_value'));

How do I change it there ?

Sorry if this is not the correct place to ask, I am completely lost in how to use this new version vs what I have already coded
Thanks for any help or pointers to the docs

Not working for nested boostrap navs

<ul class="navbar-nav ml-auto">
    <li class="nav-item active">
        <a class="nav-link" href="/">HOME <span class="sr-only">(current)</span></a>
    </li>
   <li class="nav-item">
       <a class="nav-link" data-i18n="nav.regiter" href="/registro"></a>
    </li>
<ul>

and this is the javascript

i18next.init(
  {
    lng: 'es',
    resources: {
      en: {
        translation: {
          nav: {
            register: 'register',
          },
        },
      },
      es: {
        translation: {
          nav: {
            register: 'registro',
          },
        },
      },
    },
  },
  (err, t) => {
    jqueryI18next.init(i18next, $);
    $('.navbar-nav').localize();
    $('.lang-select').click((e) => {
      i18next.changeLanguage($(e.target).text());
      $('.navbar-nav').localize();
    });
  },
);

text in navbar is not showing, the functions are being called but no text is displaying at registro nav-item, not even when it loads.
`

$.t is not a function with slow networks

🐛 Bug Report

I am getting $.t is not a function on page load only for slow network users. I could reproduce it using Google Chrome developer console, enabling the network throttle (preset Fast 3G) from the Network tab.

To Reproduce

Here is the footer of my HTML web page:

<head>
<!-- Header Scripts -->
<script type="text/javascript" src="/js/i18next.min.js"></script>
<script type="text/javascript" src="/js/jquery-i18next.min.js"></script>
<script type="text/javascript" src="/js/i18nextBrowserLanguageDetector.min.js"></script>
<script type="text/javascript" src="/js/i18nextHttpBackend.min.js"></script>
<script type="text/javascript" src="/js/ccc.js"></script>
<script>
    $(function () {
        //init i18n
        CCC.Header_TranslateBody();
    });
</script>
<!-- /CCC Header Scripts -->
</head>

<body>
<script>
$(function () {
  var alertTxt = $.t('NOTIFICATION_CENTER.LOADING_NOTIFICATIONS'); // The error happens here
});
</script>
</body>

And the content of the header ccc.js:

let CCC = window.CCC || {};
(function() {  

    const portalLng = "de-de";

    this.Header_TranslateBody = function () {
      i18next
        .use(i18nextBrowserLanguageDetector)
        .use(i18nextHttpBackend)
        .init({
          debug: true, //To comment
          fallbackLng: 'en',
          lowerCaseLng: true,
          backend: {
            loadPath: '/locales/' + portalLng +'.json'
          }
        }, function (err, t) {
          if (err) return console.error(err);
          jqueryI18next.init(i18next, $, { useOptionsAttr: true });
          i18next.changeLanguage(portalLng, () => {
            i18n_updateContent();
          });
          i18n_updateContent();
        });
    }

    this.i18n_updateContent = function () {
        $('body').localize();
    }
}).call(CCC);

Expected behavior

It looks like with slow loading times the framework loads too late. I don't know how to fix it.

Your Environment

  • runtime version: Chrome 121.0.6167.161 64 bits
  • i18next version: 23.8.2
  • os: Windows

Spaces in data-i18n value for multiple parameters

This could support to add a space after the ";" in the data-i18n attribute, such that

<input i18n-data="[value]nav.home; [placeholder]input.placeholder" />

will not result in a bug.

Currently, if this space is added, the i18next only understand the first "parameter". So, there is no option aside of don't using spaces, and this make the sintax for multiple "parameters" to be confusing to read.

i18next with razor engine

I am using jQuery i18next plugin for my asp.net mvc application with razor engine view.
somehow my UI rendering is slow. I believe the way i18n works is it traverse through DOM elements and replaces "data-i18n" attributes. so until my DOM is ready it is not replacing the elements text using i18next which is causing delay where server is talking time to return data to UI. so until data is available with UI, my localization is put on hold. is there any way to overcome this delay?

Not working with zepto

<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.js" ></script>

How hard is it to make it work with zepto?

Issue with [prepend] and [append] attributes doesn't work.

Thank you for your great job.

I found problem for the [prepend] and [append] attributes doesn't work in version 1.0.1.
My HTML is following and this works fine in version 0.2.0.

<input id="some-checkbox" type="checkbox" name="some-checkbox-group" value="hoge" checked="checked">
<label for="some-checkbox" data-i18n="[prepend]foo.bar">
  <span class="cool-effect"></span>
  <span class="cool-indicator"></span>
</label>

Because in localze process, jquery causes exception by "#[prepend]foo.bar" selector syntax error.
(invalid trimmedKey)
https://github.com/i18next/jquery-i18next/blob/master/src/index.js#L43

I know that this change depends on #19 proposal.
But I think, the proposal is so far in the different function.
Recently, HTML tag is used to make the design rich, too.
Therefore, should the library also provides to not changing HTML structure like before?

How can I use HTML tags?

I added

interpolation: {'escapeValue': false}

to init for showing an & instead of &amp; in my json.
I added it like this to my html:

<span data-i18n="html.t5"></span>

But it is not working. It shows the raw &amp;.
How can I show HTML within my json?

problem on safari with

hello
first, thanks for your help, I finally understood and got everything working.
I have now a problem due to my lack of knowledge of JS I presume
I copied my code from the docs

    i18next.use(i18nextXHRBackend).init({ 
        backend: {
       loadPath: '/locales/{{lng}}/{{ns}}.json'
   },
    long:'it',fallbackLng : 'it' }, (err, t) => {     

Everything works perfectly on Firefox and Chrome, but fails on Safari with the following error:

SyntaxError: Unexpected token '>'

which is the =>

I don't know how I should change that, could you point me in the correct direction ? thank you

i18next.amd.withJQuery missing in 18next 3.x.x

In i18next 1.x.x there was a file named i18next.amd.withJQuery
In 3.x.x version this is removed.
What is the alternative to this in latest version ?
Documentation doesn't specify anything about usage of i18next in amd modules(eg: require js)

jqueryI18next.init is not a function(…)

I have an error : jqueryI18next.init is not a function(…)
which seems be resolved ?

var i18next = require('i18next');
var i18nextInstance = i18next.createInstance();
var jqueryI18next = require('jquery-i18next');
var initialize = function () {
var router, browse;

i18next.init({
lng: 'fr',

}, function(err, t) {
// for options see
// https://github.com/i18next/jquery-i18next#initialize-the-plugin
jqueryI18next.init(i18next, $);
// start localizing, details:
// https://github.com/i18next/jquery-i18next#usage-of-selector-function
$("body").localize();
browse = BrowseApp.initialize();
return Backbone.history.start({ pushState: true });;
});

parser for parseDefaultValueFromContent

Hello,

I see in the options the flag "parseDefaultValueFromContent".

That's great.

But how to use it when parsing the html/javascript files to build up the base translations files?

Issue with data-i18n-options

Hello,
I am having difficulty using the data-i18n-options attribute on DOM elements to have variables interpolated. I tried to recreate the example from the readme however the options never seem to be passed from the attribute.
HTML:
<div id="localize_me" data-i18n="myKey" data-i18n-options="{ 'a': 'b' }"></div>

JavaScript:

jqueryI18next.init(i18next, $, {
  tName: 't', // --> appends $.t = i18next.t
  i18nName: 'i18n', // --> appends $.i18n = i18next
  handleName: 'localize', // --> appends $(selector).localize(opts);
  selectorAttr: 'data-i18n', // selector for translating elements
  targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if diffrent then itself)
  optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
  useOptionsAttr: true, // see optionsAttr
  parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
});

i18next.init({
  lng: 'en',
  debug: true,
  resources: {
    en: {
      translation: {
        "myKey": "hello world: {{a}}"
      }
    }
  }
});

$("#localize_me").localize();

Console output:

i18next::interpolator: missed to pass in variable a for interpolating hello world: {{a}}

Thanks!

i18nextHttpBackend looking 'locales' folder under main directory of the server rather than working directory

Using i18next with jQuery plugin. It is working fantastically. However, while trying to use 'i18nextHttpBackend' solution, i18next is loooking 'locales' folder under server main directory.

For example:
I am wroking at localhost/my-app
i18next.js file is located at localhost/my-app/js/i18next.js
my translation files are under at localhost/my-app/locales/en/translation.json

i18next is looking for translation.json files under localhost/locales which i believe is wrong. Even if there is an option to change it, it is not documented on jQuery page. And this should not be the default behaviour.

No sprintf post-process done after first loading.

Hi jamuhl.

I'm facing other issues with the current module.

Here is my context:

I have this function at the end of the "head" Html Tag:

<head>
...
    <script>
          function onChangeLanguage() {
              var selectedLanguage = document.getElementById("languageSelect").value;
               $('.MyTest').localize({lng: selectedLanguage});         
          }
    </script>
<head>

In the "Body" Html Tag:

<select id="languageSelect" class="MyTest" style="float:right;margin-right:20px;margin-top:1px" onchange="onChangeLanguage()">
            <option value="fr" name="language" data-i18n="French" selected></option>
            <option value="en-US" name="language" data-i18n="English"></option>
            <option value="es" name="language" data-i18n="Spanish"></option>
</select>

....
<p style="text-align:center">
        <button type="button" id="ToTest" class="btn btn-success MyTest" data-i18n="WebMail <br> by %s" data-i18n-options='{"postProcess":"sprintf", "sprintf":["A User Name"]}'> <a href="/user/login"></a></button>
</p>

And this is my configuration of i18next at the end of the "body" Html Tag:

<script type="text/javascript">
        var i18nextOptions = {
                              preload:['en-US','fr', 'es'],
                              whitelist:['en-US','fr', 'es'],
                              fallbackLng: 'en-US',
                              ns:'My_Web_Server',
                              defaultNS:'My_Web_Server',
                              nsSeparator: false,
                              keySeparator: false,
                              backend: {loadPath: '/language/static/{{lng}}/{{ns}}.json', addPath: 'language/static/add/{{lng}}/{{ns}}.json'},
                              detection: {order: ['querystring', 'cookie', 'navigator', 'localStorage'],
                                          lookupQuerystring: 'lng',
                                          lookupCookie: 'i18next',
                                          lookupLocalStorage: 'i18nextLng',
                                          caches: ['localStorage', 'cookie'],
                                          cookieMinutes: 5},
                              debug: false
                             };
        i18next
          .use(i18nextXHRBackend)
          .use(i18nextBrowserLanguageDetector)
          .use(i18nextSprintfPostProcessor)
          .init(i18nextOptions, function(err, t){

            jqueryI18next.init(i18next, $, {useOptionsAttr:true});
            $('.MyTest').localize();
          });
</script>

Well..When the page is first loaded, everything works great. But when I change the value of the dropdown (Français to Anglais ) (i.e French to English), the content of the button is translated, but the sprintf-post process seems to not working. Of course, As you can see, when the value of the dropdown is changed, it will call the javascript function "onChangeLanguage()". In this function, I'm taking the new selected value ("en-US", "fr" or "es") and I am calling $('.MyTest').localize() with in option the new language to use. But as I said, the

WebMail <br> by %s is well translated, but at the end, the sprintf post process doesn't work.

What can I do to fix this ? Is it an issue from the module ?

Thank you for your answer :-)

data-i18n not taken into consideration?

Hello,

I open this exit following this one: i18next/i18next#1124

Now that I have integrated and initialized jquery-i18n into my project, I still can't parse the "data-i18n" html tags.
I used the example of the jquery-i18n homepage, including HTML and JSON code.

Here's my entire index.js content:

import 'css/app.scss';
import $ from 'jquery';
import i18next from 'i18next';
import i18nextXHRBackend from 'i18next-xhr-backend';
import i18nextBrowserLanguageDetector from 'i18next-browser-languagedetector';
import jqueryI18next from 'jquery-i18next';
import '../translations/fr.json';
import '../translations/fr-BE.json';
import '../translations/nl.json';
import '../translations/nl-BE.json';
window.jQuery = $;
window.$ = $;

$(document).ready(function(){
  $('.header-icon').click(function(e){
    e.preventDefault();
    $('body').toggleClass('open');
  });

  $('.site-cache').click(function(e){
      $('body').removeClass('open');
  })

  i18next
    .use(i18nextXHRBackend)
    .use(i18nextBrowserLanguageDetector)
    .init({
      fallbackLng: 'fr',
      debug: true,
      backend: {
        loadPath: 'translations/{{lng}}.json',
        crossDomain: true
      }
    }, function(err, t) {
    });

    jqueryI18next.init(i18next, $, {
      tName: 't', // --> appends $.t = i18next.t
      i18nName: 'i18n', // --> appends $.i18n = i18next
      handleName: 'localize', // --> appends $(selector).localize(opts);
      selectorAttr: 'data-i18n', // selector for translating elements
      targetAttr: 'i18n-target', // data-() attribute to grab target element to translate (if diffrent then itself)
      optionsAttr: 'i18n-options', // data-() attribute that contains options, will load/set if useOptionsAttr = true
      useOptionsAttr: false, // see optionsAttr
      parseDefaultValueFromContent: true // parses default values from content ele.val or ele.text
    });

    $(".nav").localize();
    
    $('#fr').click(function() {
      i18next.changeLanguage('fr');
      /* location.reload(); */
    });

    $('#nl').click(function() {
      i18next.changeLanguage('nl');
      /* location.reload(); */
    });

});

Here's my entire index.ejs content:

<%= require('./partials/header.ejs')({ title: 'My Soccer Village' }) %>

  <button id="fr">
      FR
  </button>

  <button id="nl">
      NL
  </button>

  <ul class="nav">
    <li><a href="#" data-i18n="nav.home">Should be "Home"</a></li>
    <li><a href="#" data-i18n="nav.page1">Should be "Page One"</a></li>
    <li><a href="#" data-i18n="nav.page2">Should be "Page Two"</a></li>
  </ul>
<%= require('./partials/footer.ejs')() %>

Upgrading from i18next.amd.withJQuery - TypeError in init

I'm attempting an upgrade from the older i18next.amd.withJQuery (v1.9) to jquery-i18next (1.2), and seem to be getting a TypeError when calling init:

My init call:

var i18n  = require('i18n');
...
i18n.init({
    lng: locale,
    debug: true,
    fallbackLng: 'en'
}, function (err, t) {
    // Callback when i18next is finished initializing
    jqueryI18next.init(i18n, $);
});

TypeError:

lib/jquery-i18next.js:114 Uncaught TypeError: Cannot read property 'bind' of undefined
    at Object.init (lib/jquery-i18next.js:114)
    at initialize_i18n (js/Application.js:51)
[...etc.]

It looks like it's having problems with the line:

$[options.tName] = i18next.t.bind(i18next);

Am I missing something in my init call? Or maybe a shim in my require stuff?

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.