28

So I have this string:

var name = "Chaim";
var templateStr = "Hello, my name is ${name}";

How can I convert it into a template-string so that the result would be equal to:

var template = `Hello, my name is ${name}`;

Is there a way to programmatically construct a Template literal?

haim770
  • 48,394
  • 7
  • 105
  • 133
  • 1
    You cannot without `eval`, and I don't think you want that. Why not just use a template string in the first place? – Bergi Apr 21 '15 at 11:59
  • Because I want to pass a dynamic string to be used as the template. – haim770 Apr 21 '15 at 11:59
  • @haim770 Why can't the dynamic string be a Template literal? – thefourtheye Apr 21 '15 at 12:01
  • Because it's returned from the server as part of an Http response. – haim770 Apr 21 '15 at 12:02
  • @Bergi, Apparently, template strings already are implicitly `eval`. For example: `\`hi ${alert()}\`` – haim770 Apr 21 '15 at 12:12
  • @haim770: Yes, they are - and imo that's a problem. Where do your dynamic strings come from? – Bergi Apr 21 '15 at 12:16
  • @Bergi, As I already mentioned, they're being returned from the server (Ajax request). – haim770 Apr 21 '15 at 12:17
  • @haim770: Yeah, I meant where does the server get the strings from, who inserts them? Are they user-generated? Hard-coded? – Bergi Apr 21 '15 at 12:23
  • They are hard-coded in a resource file used for language translations. I do understand the security risk though. I guess my intention to use this mechanism as a "poor-man's templating-system" was wrong. – haim770 Apr 21 '15 at 12:26
  • 1
    This is a duplicate of http://stackoverflow.com/q/29182244/218196, but @Bergi's answer is better ;) – Felix Kling Apr 21 '15 at 13:43
  • @FelixKling: It still is imo. And Jason Orendorffs answer there nails it. – Bergi Apr 21 '15 at 13:53
  • @Bergi: Yeah. Maybe you can post your answer over there as well. Or don't. I just liked your answer :) – Felix Kling Apr 21 '15 at 13:54

1 Answers1

35

Is there a way to programmatically construct a Template literal?

No. "programmatically" and "literal" are antithetic (except you are in the realms of compilers).

Template strings should better have been named interpolated string literals or so. Please do not confuse them with templates. If you want to use dynamically created strings for templates, use a template engine of your choice.

Of course template literals might help with the implementation of such, and you might get away with something simple as

function assemble(literal, params) {
    return new Function(params, "return `"+literal+"`;"); // TODO: Proper escaping
//             ^^^^^^^^ working in real ES6 environments only, of course
}
var template = assemble("Hello, my name is ${name}", "name");
template("Chaim"); // Hello, my name is Chaim
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Bergi
  • 630,263
  • 148
  • 957
  • 1,375