Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - Evaluating template literals dynamically

Say I have template literal like so:

const templateLiteral = `string text ${expression} string text`

I want to dynamically evaluate the template literal into a finished string.

function toFoo(templateLiteral){
   //returns "string text Foo string text"
   return templateLiteral.evaluate('Foo');  
}

function toBar(templateLiteral){
  //returns "string text Bar string text"
   return templateLiteral.evaluate('Bar');  
}

function toBaz(templateLiteral){
   //returns "string text Baz string text"
   return templateLiteral.evaluate('Baz');  
}

is there a way to do something like this with template literals, or am I just being dumb? (template.evaluate() is a made up function, but I am looking for that kind of functionality with JS!).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume the best way to do this is quite obvious, simply reverse the situation given by the question. You just need to wrap the template literals in a function, and then you will delay evaluation until you pass in the desired params. It's that simple.

function evaluteTemplateLiteral(bar){
  return `foo ${bar} baz`;
}

now if you wanted to get fancier, you could create this:

function evaluateGeneric(vals, fn){
   return fn.apply(null, vals);
}

and you would use the above like so:

evaluateGeneric(['brown','fox','cholo'], function(){
    return `the quick ${arguments[0]} fox ${arguments[1]}`;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...