2

I have this constant:

.constant('SOMETHING', {
   name: `${name}`,
   subject: `${surname}`,
})

When I am trying to do this for example SOMETHING.name it says that it's undefined.

Any ideas how I can store template strings and then use it?

Thank you very much in advance.

pap
  • 115
  • 15
  • It's not `undefined`, it's `"undefined"` - there is no `name` variable anywhere in your code. – Bergi Jun 09 '16 at 13:12
  • "*how I can store template strings and then use it?*" sounds like a duplicate of [Defer execution for ES6 Template Strings](http://stackoverflow.com/q/22607806/1048572), no? – Bergi Jun 09 '16 at 13:14
  • Nothing to do with this @Bergi. I am asking how you can use template literals in constants and then use them by including the constant. – pap Jun 09 '16 at 13:17
  • Not sure what "use" refers to here. Do you mean you want to use them to define the value of a constant, or do you mean you want to expand them only later but refer to them as a constant? Please show us how you would like to "include the constant" somewhere, what results you expect and where they would come from. – Bergi Jun 09 '16 at 13:20
  • @Bergi I mean use it inside my model for instance like SOMETHING.name straight away without having to do something. Apparently though I need to create a function that replaces these ${name} with just name for example or just use $interpolate for angular use. – pap Jun 09 '16 at 13:23
  • Where would the name come from? Is it available at the time of the definition of the constant, or do you want it to be magically extracted from the model? – Bergi Jun 09 '16 at 13:25
  • @Bergi the model has default values. – pap Jun 09 '16 at 13:33

1 Answers1

2

This isn't a feature that ES6 template literals provide.

es6-template package may be used to interpolate regular JS string with template literal syntax. At this point ES6 template literal syntax has no real benefits over other template engines.

If the context is the framework (I assume that constant stands for AngularJS constant service), it may beneficial to use template facilities that the framework offers, i.e.

app.constant('SOMETHING', {
   name: '{{ name }}',
   ...
});

app.run((SOMETHING, $interpolate) => {
  let somethingName = $interpolate(SOMETHING.name)({ name: 'name' });
  ...
});
Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Seems like you are right there is no way to do this unless you either use what you have supplied or by creating a replace function that replaces the ${} with the supplied value. Thank you very much. – pap Jun 09 '16 at 13:18
  • Template literal syntax is simple enough, so yes, templates can be parsed with regexps, that's what `es6-template` basically does. – Estus Flask Jun 09 '16 at 13:23