Wednesday, 31 May 2017

Rendering translated phrase on frontend? (Trouble with exporting phrase from backend)

I'm using Google's Cloud Translation API to translate some text on the backend, which I then want to render on the frontend. However, I'm having trouble exporting the translated phrase. This is the code copy/pasted from the docs; the only thing that I added was the export.

const text = "text";
const target = "en";
translate.translate(text, target)
  .then((results) => {
    let translations = results[0];
    translations = Array.isArray(translations) ? translations : [translations];

    console.log('Translations:');
    translations.forEach((translation, i) => {
      console.log(`${text[i]} => (${target}) ${translation}`);
    });

    module.exports = translations;

  })

  .catch((err) => {
    console.error('ERROR:', err);
  });

Then, in my routes.js file, I have:

var translate = require('../translate');

router.get('/', function(req, res){
    var translate = translate;
    console.log(translate);
    res.render('index', { 'translate': translate });
});

Printing translate to the console produces "undefined."



via gridproquo

No comments:

Post a Comment