模板文字被困在一个字符串变量中 [英] Template literal trapped in a string variable

查看:154
本文介绍了模板文字被困在一个字符串变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模板 Hello,$ {user.name} 存储在一个变量中。我正在使用 fs.read 从外部文件中读取此内容。

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

现在,显然当我附加到innerHTML时一个目标div,它按原样显示字符串而不是Hello,James(假设user.name = James)。

有没有办法让它成为现实?

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}`}

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

Node.js code =>

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 =>

HTML =>

socket.on('var',function(x)){
  getElementById('target').innerHTML = x;
}


推荐答案

我稍微重写了一个解决方案在哪里

I've slightly rewritten a solution presented here.

此处, eval_template 评估作为常规字符串提供的ES6模板字符串。模板字符串中使用的本地作用域中的任何变量都需要作为第二个参数中传递的对象的属性提供(因为使用 Function 创建的函数位于全局范围内,无法访问本地变量。)

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).

这非常接近使用 eval 。您可能希望选择不同的方法来处理模板字符串。 ES6模板字符串被设计为创建字符串文字的运行时机制,而不是模板可以存储和重复使用的模板语言。

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"}}));

没有理由不能将它与标记的模板字符串一起使用,只要tag作为参数传入:

There is no reason this could not be used with a tagged template string, as long as the tag is passed in as a parameter:

eval_template("tag`${boo}`", {tag, boo});

这篇关于模板文字被困在一个字符串变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆