Typescript string interpolation with a string read from a file

I read the template lines in Typescript. I would like to know if I can use them when I read a line from a file like this:

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

If it xmlPayloadTemplatecontains a placeholder, such as ${placeholder}, is there a built-in way to do the substitution so that I can do something like:

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

?

I know a similar question about string interpolation in Javascript , but I would like to know if there is a better way to do this in Typescript.

+4
source share
2 answers

TypeScript performs string interpolation at compile time rather than run time.

. , , .

+6

Reinouts comment Lodash template. , .

Lodash :

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

.ts:

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

Source: https://habr.com/ru/post/1605770/


All Articles