5

I have read about template strings in Typescript. I'd like to know if I can use them when I've read a string from a file like this:

let xmlPayloadTemplate = fs.readFileSync('payload.xml', 'utf8');

If the xmlPayloadTemplate contains a placeholder like ${placeholder}, is there a built-in way to perform the substitution so that I can do something like:

let variableMap = {'placeholder' : 'value' }
xmlPayloadTemplate.interpolate(variableMap)

?

I'm aware of a similar question about string interpolation in Javascript but I'd like to know if there is a better way to do it in Typescript.

Community
  • 1
  • 1
reinouts
  • 384
  • 3
  • 14

2 Answers2

7

TypeScript does string interpolation at compile-time and not run-time.

You'll need to find a way to do it at run-time. You could use the code you linked to in your question or here's another example.

Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • Thanks to your link I found that Lodash offers a template function that I can use. I'll settle for that! – reinouts Sep 04 '15 at 11:10
2

Reinouts' comment pointed me to Lodash library and it's template function. Here is an example how to use it.

Add Lodash to your project:

$ npm install --save lodash
$ npm install --save @types/lodash

Then, in your .ts file:

import * as _ from "lodash";

let xmlPayloadTemplate = "Some text ${placeholder} and more text";

let variableMap = {placeholder: 'value' };

// use custom delimiter ${ }
_.templateSettings.interpolate = /\${([\s\S]+?)}/g;

// interpolate
let compiled = _.template( xmlPayloadTemplate );
let xmlPayloadCompiled = compiled( variableMap );

// show me
alert(xmlPayloadCompiled);
evo
  • 81
  • 1
  • 3