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
946 views
in Technique[技术] by (71.8m points)

javascript - Template literal trapped in a string variable

I have a template Hello, ${user.name} stored in a variable. I am reading this from an external file using fs.read.

Now, obviously when I attach to the innerHTML of a target div, it shows the string as it is and not "Hello, James" (assuming user.name = James) as intended.
Is there a way to make it happen?

extfile.txt =>
{"A":"`Welcome, ${user.name}`"}

Node.js code =>

fs.readFile(__dirname + '/extfile.txt', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  } else {
    let x = JSON.parse(data);
    socket.emit('var',x.A);
  }
});

HTML =>

socket.on('var',function(x)){
  getElementById('target').innerHTML = x;
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I've slightly rewritten a solution presented here.

Here, eval_template evaluates an ES6 template string provided as a regular string. Any variable in local scope used in the template string needs to be provided as a property of the object passed in the second parameter (because functions created using Function are in the global scope and cannot access local variables).

This is perilously close to using eval. You might want to choose a different approach to handling your template strings. ES6 template strings are designed to be a run-time mechanism to create string literals, not a templating language whose templates can be stored and re-used.

function eval_template(s, params) {
  return Function(...Object.keys(params), "return " + s)
    (...Object.values(params));
}

const template = "`Welcome, ${user.name}`";
console.log(eval_template(template, {user: {name: "James"}}));

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

...