0

I need to dynamically translate 2 strings to Spanish in the following JS, namely "Date" and "Read more" if the html-document's language code is set to Spanish (html lang="es"):

$.each(data,function(post, postInfo) {
        jsonArray.push( postEntry + '<a href="' + postInfo.link + '" class="preview-title"><h2>' + postInfo.title + '</h2></a><div class="preview-meta">Date: ' + postInfo.date + '</div><p>' + postInfo.preview + '...</p><div class="read-more"><a href="' + postInfo.link + '" class="link-button">Read more</a></div>' + postFooter);
      });

I am unsure how to approach this in the best way.

Getting the language code as a string would probably work with this:

var languageCode = $('html').attr('lang');

And then you could implement a simple check like:

if (languageCode === 'es') {
 ...
} else {
 ...
}

Would appreciate your advice how to approach this.

  • Translation is typically done on the server, or before template generation. – zzzzBov Sep 12 '16 at 19:35
  • Look into translation libraries. I've used i18next but there are bound to be more - these allow you to define translations for however many languages you want. In general, with internationalisation you'll have to only be storing _keys_ that are going to be translated to either English or Spanish (or any other language you want to use). – VLAZ Sep 12 '16 at 19:35
  • check this question: http://stackoverflow.com/questions/4886319/replace-text-in-html-page-with-jquery – MrMisery Sep 12 '16 at 19:36
  • Problem in this case is that this is part of an AJAX call, where most of the markup is generated in the JS... The outputted variables are all available translated from the server. It's just these couple of strings in the JS that need a translation... –  Sep 12 '16 at 19:42
  • I'd recommend using http://i18next.com/ instead of rolling your own. – Asad Saeeduddin Sep 12 '16 at 19:54

1 Answers1

1

if you only want to translate 2 kind of words - translation library might be overkill.

I would do something like

lang = {
    es : {
        readmore : 'Read More In Spanish',
        date     : 'Date in spanish'
    },
    en : {
        readmore : 'Read More',
        date     : 'Date'            
    }
}

var languageCode = $('html').attr('lang');

console.log(lang[languageCode].readmore)
console.log(lang[languageCode].date)
naortor
  • 2,019
  • 12
  • 26