diff --git a/.travis.yml b/.travis.yml index 5b1afe90..2465405e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,7 @@ language: node_js sudo: false node_js: - - "0.10" - - "0.12" - "4" - - "5" + - "6" - "node" after_success: npm run coverage diff --git a/README.md b/README.md index 9859458f..32866589 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,19 @@ output: `my awesome string foo` +_using tagged template literals_ + +```js +var __ = require('y18n').__ +var str = 'foo' + +console.log(__`my awesome string ${str}`) +``` + +output: + +`my awesome string foo` + _pluralization support:_ ```js @@ -60,6 +73,10 @@ Create an instance of y18n with the config provided, options include: Print a localized string, `%s` will be replaced with `arg`s. +This function can also be used as a tag for a template literal. You can use it +like this: __`hello ${'world'}`. This will be equivalent to +`__('hello %s', 'world')`. + ### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) Print a localized string with appropriate pluralization. If `%d` is provided diff --git a/index.js b/index.js index 91b159e3..922f8c49 100644 --- a/index.js +++ b/index.js @@ -16,6 +16,9 @@ function Y18N (opts) { } Y18N.prototype.__ = function () { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral.apply(this, arguments) + } var args = Array.prototype.slice.call(arguments) var str = args.shift() var cb = function () {} // start with noop. @@ -40,6 +43,19 @@ Y18N.prototype.__ = function () { return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args)) } +Y18N.prototype._taggedLiteral = function (parts) { + var args = arguments + var str = '' + parts.forEach(function (part, i) { + var arg = args[i + 1] + str += part + if (arg) { + str += '%s' + } + }) + return this.__.apply(null, [str].concat([].slice.call(arguments, 1))) +} + Y18N.prototype._enqueueWrite = function (work) { this.writeQueue.push(work) if (this.writeQueue.length === 1) this._processWriteQueue() diff --git a/test/locales/pirate.json b/test/locales/pirate.json index 9683dd25..d7f16e29 100644 --- a/test/locales/pirate.json +++ b/test/locales/pirate.json @@ -1,5 +1,6 @@ { "Hello": "Avast ye mateys!", + "Hi, %s %s!": "Yarr! Shiver me timbers, why 'tis %s %s!", "%d cat": { "one": "%d land catfish", "other": "%d land catfishes" diff --git a/test/y18n-test.js b/test/y18n-test.js index 53499554..089746ff 100644 --- a/test/y18n-test.js +++ b/test/y18n-test.js @@ -30,6 +30,14 @@ describe('y18n', function () { }) describe('__', function () { + it('can be used as a tag for template literals', function () { + var __ = y18n({ + locale: 'pirate', + directory: path.join(__dirname, 'locales') + }).__ + + __`Hi, ${'Ben'} ${'Coe'}!`.should.equal('Yarr! Shiver me timbers, why \'tis Ben Coe!') + }) it('uses replacements from the default locale if none is configured', function () { var __ = y18n({ directory: path.join(__dirname, 'locales')