javascript - output translations without document.write -
i understand document.write
evil , should not used output text on website.
however, did not find better solution yet usage, output translated text via javascript on page. consider this:
my template code looks this:
<h1><script>_e("title");</script></h1>
in javascript file have similar code translate strigs:
// initialize dictionaries , set current language. window.lang = {}; window.lang.en = { "title": "sample page" }; window.lang.de = { "title": "beispiel seite" }; window.curlang = "en"; // translation function should output translated text. function _e(text) { var dictionary = window.lang[window.curlang]; var translation = dictionary[text]; // below line evil. // what's alternative without having change template code above? document.write( translation ); }
question:
can change javascript function not use document.write
work without changing template code? if not: best solution translation here?
this first time using document.currentscript i've tried code , should work correctly:
<!doctype html> <html> <head> <title></title> <script type="text/javascript" charset="utf-8"> // initialize dictionaries , set current language. window.lang = {}; window.lang.en = { "title": "sample page" }; window.lang.de = { "title": "beispiel seite" }; window.curlang = "en"; // translation function should output translated text. function _e(text) { var dictionary = window.lang[window.curlang]; var translation = dictionary[text]; var container = document.currentscript; container.parentnode.innerhtml = translation; } </script> </head> <body> <h1><script>_e("title");</script></h1> </body> </html>
another why use special tags or attribute replace jquery, change template. like
<span class='i18n-text'>title</span> var dictionary = window.lang[window.curlang]; jquery('.i18n-text').each(function(){ var text = $(this).text(); var translation = dictionary[text]; $(this).html(translation); });
(i haven't tried second solution should work :d)
Comments
Post a Comment