Skip to content

Instantly share code, notes, and snippets.

@okunishinishi
Created August 8, 2015 03:38
Show Gist options
  • Save okunishinishi/6ab5beecc86b6128fdd8 to your computer and use it in GitHub Desktop.
Save okunishinishi/6ab5beecc86b6128fdd8 to your computer and use it in GitHub Desktop.
Node.jsでのメッセージリソース管理を考える ref: http://qiita.com/okunishinishi@github/items/68b3c8e12ea8f5741387
{
"TITLE": "オクニシタカドットコム",
"WELCOME_MESSAGE": "オクニシタカドットコムへようこそ"
}
<html>
<head><title>{{msg.TITLE}}</title></head>
<body><h1>{{msg.WELCOME_MESSAGE}}</body>
</html>
exports.TITLE = "オクニシタカドットコム";
exports.WELCOME_MESSAGE = exports.TITLE + "へようこそ"
{
"TITLE": "オクニシタカドットコム",
"WELCOME_MESSAGE": "#{TITLE}へようこそ"
}
var locale = evaljson({
keys: {
"NAME": "My Awesome App"
},
titles: {
"WELCOME_TITLE": "Welcome to #{keys.NAME}!"
},
/*...*/
});
console.log(locale.titles['WELCOME_TITLE']); //-> Welcome to My Awesome App!
var flattened = flatten({
'foo': {'bar': 'baz'}
});
console.log(flattened); // => {'foo.bar': 'baz'}
function flatten(nested) {
var flattened = {};
Object.keys(nested || {}).forEach(function (key) {
var value = nested[key];
switch (typeof(value)) {
case 'string':
case 'number':
case 'function':
flattened[key] = value;
break;
default:
var subValues = flatten(value);
Object.keys(subValues).forEach(function (subKey) {
var fullKey = [key, subKey].join('.');
flattened[fullKey] = subValues[subKey];
});
break;
}
});
return flattened;
}
function _embed(src, values) {
var dest = extend({}, src);
Object.keys(dest).forEach(function (key) {
var value = dest[key];
switch (typeof(value)) {
case 'object':
dest[key] = _embed(value, values);
break;
case 'string':
dest[key] = value.replace(/(#\{)(.*?)(\})/g, function ($0, $1, $2) {
var valid = values.hasOwnProperty($2);
if (valid) {
return values[$2];
} else {
throw new Error('Unknown expression:' + $2);
}
});
break;
default:
break;
}
});
return dest;
}
var dict = flatten(src); // Use flatten object as dictionary.
var parsed = _embed(src, flatten(src));
console.log(parsed);
$ npm install evaljson --save
var evaljson = require('evaljson');
var locale = evaljson({
keys: {
"NAME": "My Awesome App"
},
titles: {
"WELCOME_TITLE": "Welcome to #{keys.NAME}!" // Embed value.
},
/*...*/
});
console.log(locale.titles['WELCOME_TITLE']); //-> Welcome to My Awesome App!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment