Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 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 Answer

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]}`;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...