Security News
ESLint is Now Language-Agnostic: Linting JSON, Markdown, and Beyond
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
i18next-text
Advanced tools
Using i18next translations without having the `key` as strings, you do not need to worry about i18n key naming.
Using i18next translations without the need to maintain i18n keys.
It's recommended to use i18next-scanner as a Gulp or Grunt plugin to scan your code, extract translation keys/values, and merge them into i18n resource files.
i18n._('Save your time and work more efficiently.');
Check out our demo on JSFiddle.
With bower:
bower install i18next-text
With npm:
npm install i18next-text
Normally i18next-text can be initialized with options by calling i18nText.init(): ```javascript` // You can omit this step if using default options i18nText.init({ debug: true, // default: false hash: 'sha1' // default: 'sha1' });
Then extends i18n object to provide a new _() method:
```javascript
i18n._ = i18nText._;
Initializes i18next with options:
i18n.init({lng: 'en'});
// later
i18n.t('key');
i18n._('It is no longer needed by specifying the key.');
or initializes i18next with both options and callback:
i18n.init({lng: 'en'}, function(t) {
i18n.t('key');
i18n._('It is no longer needed by specifying the key.');
});
For example, assume that you have the following directory structure:
index.html
vendor/
i18next.js
i18next-text.js
i18n/
en/
resource.json
de/
resource.json
index.html
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
</head>
<body>
<script src="vendor/i18next.js"></script>
<script src="vendor/i18next-text.js"></script>
<script>
// See "Browser globals" below for example
</script>
</body>
</html>
English resource file (i18n/en/resource.json):
{
"loading": "Loading...",
"b04ba49f848624bb97ab094a2631d2ad74913498": "Loading..."
}
German resource file (i18n/de/resource.json):
{
"loading": "Wird geladen...",
"b04ba49f848624bb97ab094a2631d2ad74913498": "Wird geladen..."
}
All SHA-1 keys are automatically generated using i18next-scanner. You do not need to maintain resource files.
var i18n = require('i18next');
var i18nText = require('i18next-text');
var options = {
lng: 'en',
preload: ['en', 'de'],
load: 'current',
fallbackLng: false,
resGetPath: 'i18n/__lng__/__ns__.json',
ns: {
namespaces: [
'resource' // default
],
defaultNs: 'resource'
}
};
// extends i18n object to provide a new _() method
i18n._ = i18nText._;
i18n.init(options, function() {
i18n.t('loading'); // will return "Loading..."
i18n._('Loading...', {lng: 'de'}); // will return "Wird geladen..."
});
(function(root) {
var i18n = root.i18n;
var i18nText = root.i18nText;
var options = {
lng: 'en',
preload: ['en', 'de'],
load: 'current',
fallbackLng: false,
resGetPath: 'i18n/__lng__/__ns__.json',
ns: {
namespaces: [
'resource' // default
],
defaultNs: 'resource'
}
};
// extends i18n object to provide a new _() method
i18n._ = i18nText._;
i18n.init(options, function() {
i18n.t('loading'); // will return "Loading..."
i18n._('Loading...', {lng: 'de'}); // will return "Wird geladen..."
});
}(this));
i18next-text supports most i18next features, for example:
Access value in different language:
i18n._('Loading...', {lng: 'de'}); // will get value in de instead of en
Replacing variables:
i18n._('YouTube has more than __count__ billion users.', {count: 1});
Visit http://i18next.com/pages/doc_features.html to see more examples.
You can call the key() function to get the hashed key with a given string:
var i18nText = require('i18next-text');
i18nText.key('Loading...'); // will return a hash string
var i18nText = require('i18next-text');
i18nText.exists('Loading...'); // will return a boolean value
var strNotTranslated = '<span class="highlight error">STRING_NOT_TRANSLATED</span>';
i18n._('YouTube has more than one billion users each month.', {
lng: 'de',
defaultValue: strNotTranslated
});
It will produce the following output if above string is not available in de
translation:
<span class="highlight error">STRING_NOT_TRANSLATED</span>
You can see a demo here.
You can explicitly specify a default key of a text string by passing a defaultKey
option:
i18n._('Loading...', {defaultKey: 'loading'});
i18n._('Loading...', {defaultKey: 'b04ba49f848624bb97ab094a2631d2ad74913498'});
Note. Missing resources can be sent to server by turning on i18next's sendMissing option like below:
i18n.init({sendMissing: true});
You can customize your own hash function by including the i18next-text.custom.js file, which is only 2KB in size:
<script src="vendor/i18next.js"></script>
<script src="vendor/i18next-text.custom.js"></script>
In your initialization script, change hash
on i18nText.init() to apply a custom hash function:
i18nText.init({
hash: function(str) {
return customHashFunction(str);
}
});
i18next-text provides built-in support for Handlebars helper. You can register the i18n
helper for use in templates.
Use the Handlebars.registerHelper
method to register the i18n
helper:
var i18nText = require('i18next-text');
var handlebars = require('handlebars');
handlebars.registerHelper('i18n', i18nText.handlebarsHelper);
By default, Handlebars will escape the returned result by default.
If you want to generate HTML, you have to return a new Handlebars.SafeString(result)
like so:
var i18nText = require('i18next-text');
var handlebars = require('handlebars');
handlebars.registerHelper('i18n', function() {
var result = i18nText.handlebarsHelper.apply(this, arguments);
return new handlebars.SafeString(result);
});
In such a circumstance, you will want to manually escape parameters.
Here is an example of what our template file might look like:
{{i18n 'Basic Example'}}
{{i18n '__first-name__ __last-name__' first-name=firstname last-name=lastname}}
{{i18n 'English' defaultKey='locale:language.en-US'}}
{{i18n defaultKey='loading'}}
{{#i18n}}Some text{{/i18n}}
{{#i18n this}}Description: {{description}}{{/i18n}}
{{#i18n this last-name=lastname}}{{firstname}} __last-name__{{/i18n}}
You can compile the template string into a Handlebars template function, and then render the template by passing a data object (a.k.a. context) into that function:
var source = fs.readFileSync('./handlebars-helper-i18n.hbs'), 'utf-8');
var template = handlebars.compile(source);
var context = {
'firstname':'Foo',
'lastname':'Bar',
'description': 'Foo Bar Test'
};
console.log(template(context));
You will see console output like so:
Basic Example
Foo Bar
English
Loading...
Some text
Description: Foo Bar Test
Foo Bar
You can see a demo here.
Copyright (c) 2015 Cheton Wu
Licensed under the MIT License.
FAQs
Using i18next translations without having the `key` as strings, you do not need to worry about i18n key naming.
The npm package i18next-text receives a total of 17 weekly downloads. As such, i18next-text popularity was classified as not popular.
We found that i18next-text demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint has added JSON and Markdown linting support with new officially-supported plugins, expanding its versatility beyond JavaScript.
Security News
Members Hub is conducting large-scale campaigns to artificially boost Discord server metrics, undermining community trust and platform integrity.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.