Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I construct a Template String from a regular string? [duplicate]

Tags:

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?

like image 767
haim770 Avatar asked Apr 21 '15 11:04

haim770


People also ask

What is a string template?

What is StringTemplate? StringTemplate is a java template engine (with ports for C#, Objective-C, JavaScript, Scala) for generating source code, web pages, emails, or any other formatted text output.


1 Answers

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 
like image 162
Bergi Avatar answered Sep 19 '22 16:09

Bergi