Skip to content

Commit

Permalink
introduce new option skipOnVariables to fix #1479 (#1483)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrai committed Jul 11, 2020
1 parent 44c2e76 commit 26d5719
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/Translator.js
Expand Up @@ -290,6 +290,15 @@ class Translator extends EventEmitter {
...options,
...{ interpolation: { ...this.options.interpolation, ...options.interpolation } },
});
const skipOnVariables =
(options.interpolation && options.interpolation.skipOnVariables) ||
this.options.interpolation.skipOnVariables;
let nestBef;
if (skipOnVariables) {
const nb = res.match(this.interpolator.nestingRegexp);
// has nesting aftbeforeer interpolation
nestBef = nb && nb.length;
}

// interpolate
let data = options.replace && typeof options.replace !== 'string' ? options.replace : options;
Expand All @@ -298,6 +307,12 @@ class Translator extends EventEmitter {
res = this.interpolator.interpolate(res, data, options.lng || this.language, options);

// nesting
if (skipOnVariables) {
const na = res.match(this.interpolator.nestingRegexp);
// has nesting after interpolation
const nestAft = na && na.length;
if (nestBef < nestAft) options.nest = false;
}
if (options.nest !== false)
res = this.interpolator.nest(
res,
Expand Down
1 change: 1 addition & 0 deletions src/defaults.js
Expand Up @@ -73,6 +73,7 @@ export function get() {
// nestingSuffixEscaped: ')',
// defaultVariables: undefined // object that can have values to interpolate on - extends passed in interpolation data
maxReplaces: 1000, // max replaces to prevent endless loop
skipOnVariables: false,
},
};
}
Expand Down
58 changes: 58 additions & 0 deletions test/i18next.interpolation.skipOnVariables.spec.js
@@ -0,0 +1,58 @@
import i18next from '../src/i18next.js';

const instance = i18next.createInstance();

describe('i18next.interpolation.nesting', () => {
before(done => {
instance.init(
{
lng: 'en',
interpolation: {
skipOnVariables: true,
},
resources: {
en: {
translation: {
key: 'value {{a}}',
keyWithoutVar: 'value',
nested: 'nested stuff',
keyWithNest: '$t(nested2) value',
keyWithNestAndVar: '$t(nested2) value {{a}}',
nested2: 'HI',
},
},
},
},
() => {
done();
},
);
});

describe('nesting', () => {
var tests = [
{
args: ['keyWithoutVar'],
expected: 'value',
},
{
args: ['key', { a: 'hahaha' }],
expected: 'value hahaha',
},
{
args: ['keyWithNest'],
expected: 'HI value',
},
{
args: ['keyWithNestAndVar', { a: '$t(nested)' }],
expected: '$t(nested2) value $t(nested)',
},
];

tests.forEach(test => {
it('correctly nests for ' + JSON.stringify(test.args) + ' args', () => {
expect(instance.t.apply(instance, test.args)).to.eql(test.expected);
});
});
});
});

0 comments on commit 26d5719

Please sign in to comment.