-2

I'd like to do something like this:

let template = `The first value is ${v1} and the second value is ${v2}`;
template.interpolate(v1,v2);

Is this possible in Javascript / Typescript? The documentation I've found contains the variables being interpolated into the template within the same context that the template string is created in.

As indicated in the comments there are a lot of ways to do this in Javascript, but I'm specifically wondering whether we can create predefined templates with backticks? For example the duplicate link uses quotes, which do not support multiline template markup.

Ole
  • 41,793
  • 59
  • 191
  • 359
  • 1
    Possible duplicate of [Convert a string to a template string](https://stackoverflow.com/questions/29182244/convert-a-string-to-a-template-string) – jonrsharpe Jun 25 '18 at 18:59
  • Convert a string to a template string does not use backticks in the template ... – Ole Jun 25 '18 at 19:00

2 Answers2

1

According to the MDN template literals reference you can create your own templates using backticks, please refer to the Tagged Templates section.

Adapting to your example:

function template(strings, ...keys) {
  return function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  };
}

var interpolate = template`The first value is ${'v1'} and 
the second value is ${'v2'}`;

interpolate({ v1: 1, v2: 2 });

Whose output should be:

The first value is 1 and
the second value is 2

Hope it helps

Rodrigo Ferreira
  • 1,091
  • 8
  • 11
1

Thanks @RodrigoFerreira. I read up on the template literals section and your answer and realized that it's as simple as defining a function and passing that around instead of using a direct template literal:

const f = (v1:any)=> {
    return `v1 is ${v1}`;
}

console.log(f("Howdy Rodrigo!")); //logs v1 is Howdy Rodrigo!
Ole
  • 41,793
  • 59
  • 191
  • 359