0

I am working on an application where we have a number of languages. We are not using a package like 'i18n' but instead -- since the number of string literals isn't so large -- using a system like this:

// constants
const GREETING = 'greeting'

// es.js -- a language object

const aLanguageObject = {[GREETING] : '¿Cómo estás?'}

// helper function
const getText(selector) = currentLanguageObject[selector]

// usage file
const greetingPhrase = getText(GREETING);

where currentLanguageObject is one of es.js, en.js, etc, that is, one of the languageObjects already defined (we select based on a process.env value)

We'd like to be able to make use of tagged template literals to interpolate values into these template literals saved as constants.

I've tried to make tagged template literals work with our system like this:

// en.js
    const aLanguageObject = {[CONFIRM_NUMBER] : `is the number ${0} correct?`}

and then use tagged templates like this 

    const theNumber = 12;

    const   myTag = (strings, numberExp) => `${strings[0]}${theNumber}${strings[1]}`;

    const numberConfirmString = myTag`${getText(CONFIRM_NUMBER)})`;

but numberConfirmString is undefined.

Is there a way to "fill in" template literals saved as constants?

halfer
  • 19,824
  • 17
  • 99
  • 186
Cerulean
  • 5,543
  • 9
  • 59
  • 111

1 Answers1

1

The syntax:

const obj = {[key] = value}

Should be:

const obj = {[key]: value}

otherwise, a SyntaxError arises.

Apart of this, I think that something like this should work:

function generaTemplate (strings, ...keys) {
  return function(data) {
    let temp = strings.slice();
    keys.forEach((key, i) => {
      temp[i] = temp[i] + data[key];
    });
    return temp.join('');
  }
}

const userTpl = user => generaTemplate`<article>
  <p>Name: ${'name'}</p>
  <p>Age: ${'age'}</p>
</article>`(user);

const users = [{
  name: 'Eric',
  age: '10'
}, {
  name: 'Rob',
  age: '20'
}];

const usersList = users.reduce((acc, user) => {
  return acc + userTpl(user);
}, '');

console.log(usersList);

It returns this:

<article>
  <p>Name: Eric</p>
  <p>Age: 10</p>
</article><article>
  <p>Name: Rob</p>
  <p>Age: 20</p>
</article>

As alternative, you can also use:

const welcome = param => `Hello, ${param}`;
console.log(welcome('world'));

Output:

Hello, world

Check this: Defer execution for ES6 Template Literals

Eric
  • 1,469
  • 1
  • 13
  • 11