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.

5
  • Translation is typically done on the server, or before template generation. Commented Sep 12, 2016 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). Commented Sep 12, 2016 at 19:35
  • check this question: stackoverflow.com/questions/4886319/… Commented Sep 12, 2016 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... Commented Sep 12, 2016 at 19:42
  • I'd recommend using i18next.com instead of rolling your own. Commented Sep 12, 2016 at 19:54

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.