问题描述
所以我有这个字符串
:
var name = "Chaim";
var templateStr = "Hello, my name is ${name}";
如何将其转换为模板字符串,以便结果等于: p>
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?
推荐答案
不。 程式化和文字是对立的(除了你在编译器的领域)。
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
这篇关于如何从常规字符串构造模板字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!