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

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

问题描述

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

现在,很明显,当我附加到目标 div 的 innerHTML 时,它按原样显示字符串,而不是按预期显示Hello, James"(假设 user.name = James).
有没有办法让它发生?

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

Node.js 代码 =>

<前>fs.readFile(__dirname + '/extfile.txt', 'utf8', function (err,data) {如果(错误){返回 console.log(err);} 别的 {让 x = JSON.parse(data);socket.emit('var',x.A);}});

HTML =>

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

解决方案

我稍微重写了一个解决方案 此处.

此处,eval_template 计算作为常规字符串提供的 ES6 模板字符串.模板字符串中使用的局部范围内的任何变量都需要作为传递给第二个参数的对象的属性提供(因为使用 Function 创建的函数在全局范围内,不能访问局部变量).

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

function eval_template(s, params) {return Function(...Object.keys(params), "return " + s)(...Object.values(params));}const template = "`欢迎,${user.name}`";console.log(eval_template(template, {user: {name: "James"}}));

没有理由不能将其与带标签的模板字符串一起使用,只要将标签作为参数传入即可:

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

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

解决方案

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

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天全站免登陆