feat: Support nested locale keys.
Example:
```js
{
model: {
user: {
name: 'Real Name',
createdAt: 'Joined At'
}
}
}
```
```js
ctx.__('model.user.name');
ctx.__('model.user.createdAt');
```
The before:
```js
{
'model.user.name': 'Real Name',
'model.user.createdAt', 'Joined At'
}
```
Benchmarks:
```
Deeps: 9
2 tests completed.
direct read a key x 85,993,593 ops/sec ±1.89% (96 runs sampled)
by nested x 4,203,837 ops/sec ±0.98% (93 runs sampled)
```
This commit is contained in:
12
index.js
12
index.js
@@ -103,7 +103,8 @@ module.exports = function (app, options) {
|
||||
|
||||
var locale = this.__getLocale();
|
||||
var resource = resources[locale] || {};
|
||||
var text = resource[key] || key;
|
||||
|
||||
var text = resource[key] || getNestedValue(resource, key) || key;
|
||||
debug('%s: %j => %j', locale, key, text);
|
||||
if (!text) {
|
||||
return '';
|
||||
@@ -209,4 +210,13 @@ module.exports = function (app, options) {
|
||||
// support zh_CN, en_US => zh-CN, en-US
|
||||
return locale.replace('_', '-').toLowerCase();
|
||||
}
|
||||
|
||||
// fetch nested key, example: model.user.fields.title
|
||||
function getNestedValue(data, key) {
|
||||
var keys = key.split('.');
|
||||
for (var i = 0; typeof data === 'object' && i < keys.length; i++) {
|
||||
data = data[keys[i]];
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user