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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With