6

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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to your link I found that Lodash offers a template function that I can use. I'll settle for that!
3

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.