Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolate string with dynamic data with angular2

I'm loading up data from the server via ajax requests. The JSON file has configurations for popups in the site.

popupData: {
   data:{ var_one: "hello", var_two: "world"},
   template: "the <b>{{var_two}}</b> say's {{var_one}}"
}

The variable names and template will be different for every occurrence of the popup.

How can I get this string interpolated with the data that comes with it? I need to pass the pre-built string to a component to be viewed using [innerHTML].

like image 483
Mike Roberts Avatar asked Apr 10 '17 16:04

Mike Roberts


1 Answers

Somewhere after the data was received:

const popupString = popupData.template.replace(
  /{{\s?([^{}\s]*)\s?}}/g,
  (substring, parsedKey) => {
    const replacer = popupData.data[parsedKey];
    return typeof replacer !== 'undefined' ? replacer : substring;
  }
);

It should equal the <b>world</b> says Hello in your example.

Please note that this code comes from robisim74’s angular-l10n (MIT license).

like image 178
gsc Avatar answered Oct 29 '22 14:10

gsc