Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in Typescript with string read from file

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.

like image 884
reinouts Avatar asked Sep 03 '15 15:09

reinouts


2 Answers

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.

like image 118
David Sherret Avatar answered Oct 14 '22 22:10

David Sherret


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);
like image 28
evo Avatar answered Oct 14 '22 22:10

evo