Skip to content

Instantly share code, notes, and snippets.

@danielronnkvist
Last active October 15, 2015 13:51
Show Gist options
  • Save danielronnkvist/383858e38494bd36cccc to your computer and use it in GitHub Desktop.
Save danielronnkvist/383858e38494bd36cccc to your computer and use it in GitHub Desktop.
Puts text from config file into html. Just add an translate attribute followed by the keys separated by dashes,for example: <h1 translate-header-title> will get config['header']['title'].
Translation = (config)->
if typeof config != "object"
throw 'Error, config is not an object'
paths = []
iterate = (obj, parent, paths)->
for property of obj
if obj.hasOwnProperty(property)
if parent != ''
new_parent = parent + '-' + property
else
new_parent = property
if typeof obj[property] == "object"
iterate(obj[property], new_parent, paths)
else
paths.push {key: new_parent, text: obj[property]}
iterate(config, '', paths)
console.log paths
for conf in paths
elems = document.querySelectorAll('[translate-' + conf.key + ']')
for elem in elems
elem.innerText = conf.text
t = new Translation({fitForKing: {title: 'FIT FOR A KING', body: 'Lorem ipsum Nisi amet aliqua nostrud Duis minim enim esse dolore minim est aliquip sint esse pariatur velit non laboris velit nulla cillum eu consequat nulla elit.'}})
var Translation, t;
Translation = function(config) {
var conf, elem, elems, i, iterate, len, paths, results;
if (typeof config !== "object") {
throw 'Error, config is not an object';
}
paths = [];
iterate = function(obj, parent, paths) {
var new_parent, property, results;
results = [];
for (property in obj) {
if (obj.hasOwnProperty(property)) {
if (parent !== '') {
new_parent = parent + '-' + property;
} else {
new_parent = property;
}
if (typeof obj[property] === "object") {
results.push(iterate(obj[property], new_parent, paths));
} else {
results.push(paths.push({
key: new_parent,
text: obj[property]
}));
}
} else {
results.push(void 0);
}
}
return results;
};
iterate(config, '', paths);
console.log(paths);
results = [];
for (i = 0, len = paths.length; i < len; i++) {
conf = paths[i];
elems = document.querySelectorAll('[translate-' + conf.key + ']');
results.push((function() {
var j, len1, results1;
results1 = [];
for (j = 0, len1 = elems.length; j < len1; j++) {
elem = elems[j];
results1.push(elem.innerText = conf.text);
}
return results1;
})());
}
return results;
};
t = new Translation({
fitForKing: {
title: 'FIT FOR A KING of bajs',
body: 'Lorem ipsum Nisi amet aliqua nostrud Duis minim enim esse dolore minim est aliquip sint esse pariatur velit non laboris velit nulla cillum eu consequat nulla elit.'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment