place javascript variables in html - several ways, which one to choose? -
i'm on html have place variables in depency of language choosen user. several reasons able client-side.
i have figured out different ways so, i'm asking myself best way (best way in case means "fastest", "most fail-safe" , on).
the variables stored in json-file looking this:
lang = { "nav" : { "categories" : { "header" : { "de" : "kategorien", "en" : "categories" }, }, "search" : { "placeholder" : { "de" : "suchen nach...", "en" : "search for..." }, "button" : { "de" : "finden", "en" : "find" }, }, }, "benefits" : { "first" : { "title" : { "de" : "irgendwas", "en" : "something" }, "content" : { "de" : "blablabla", "en" : "blablabla in english" }, }, "second" : { "title" : { "de" : "irgendwas anderes", "en" : "something else" }, "content" : { "de" : "noch mehr blablabla", "en" : "some more blablabla in english" }, }, }, }
now place variables directly using little script everywhere shall be, example:
<script>document.write(lang.nav.search.button[language])</script>
on other side instead of script place
<span id="lang.nav.search.button"></span>
or other tag , have external javascript replace/append/prepend or whatever.
to make bit more complicated, in cases have set attributes of elements in dependency of choosen language, , because direct execution of script above inside tag set attribute isn't possible (or there way so?) use function parent element of current position in dom
function scriptparent() { var scripts = document.getelementsbytagname('script'); return scripts[scripts.length - 1].parentnode; };
and set attribute this:
<div class="form-group"> <input type="text" class="form-control"> <script>scriptparent().firstelementchild.placeholder = lang.nav.search.placeholder[language];</script> </div>
when finished project there between 50 - 100 variables, so, suggestion way prefer? or maybe has better way deal it?
thanks in advance!
you can use http://i18next.com/ library translations. use template library, mustache, handlebars or similar.
Comments
Post a Comment