Last active
March 10, 2017 09:34
-
-
Save kristian76/612fe847b1359d8a3c90baaef5de6c94 to your computer and use it in GitHub Desktop.
Javascript L10N idea, how to handle translations in Javascript and being able to serve the translations in a simple structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Structure of the translations is a simple | |
* key value storage | |
*/ | |
var L10N = { | |
"hello_kitty": "hej killing" | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The src file that's bundled into /dist/js/l10n.js | |
*/ | |
module.exports = { | |
String.prototype.l10n = function(l) { | |
var _this = this, | |
// key = _this.toLowerCase().replaceAll(/\s/, "_"); | |
key = _this; | |
if (Object.keys(L10N).includes(key)) { | |
return L10N[key]; | |
} | |
return _this.toString(); | |
}; | |
String.prototype.replaceAll = function(search, replacement) { | |
var _this = this; | |
return _this.replace(new RegExp(search, 'g'), replacement); | |
}; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="da"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Hello Kitty</title> | |
<link rel="localization" hreflang="da-DK" href="danish.json" type="application/x-l10n+json"/> | |
<script src="/js/l10n.js"></script> | |
</head> | |
<body> | |
<script> | |
// Shows hej killing | |
document.write("hello_kitty".l10n("da_DK")); | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
*/ | |
var assert = require("assert"); | |
var String = require("../dist/js/l10n.js"); | |
describe("I10L", function() { | |
/** | |
* Global data | |
*/ | |
var L10N = { | |
"hello_kitty": "hej killing" | |
}; | |
beforeEach(function() { | |
global.L10N = L10N; | |
}); | |
afterEach(function() { | |
delete global.L10N; | |
}); | |
// Something | |
describe("L10N", function () { | |
it("should return hej killing", function() { | |
assert.equal("hej killing", "hello_kitty".l10n("da_DK")); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment