简体   繁体   English

如何在ES6中嵌套模板字符串?

[英]How to nest template strings in ES6?

I got an prefer-template error from eslint. 我从eslint得到了一个prefer-template错误。 For the workaround, I changed my code to use a template string inside the require function which is nested inside the url function as following: 对于变通方法,我更改了我的代码以在require函数中使用模板字符串,该函数嵌套在url函数中,如下所示:

{
  background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png` center no-repeat`)})
}

However, that gave an error, obviously. 但是,这显然是错误的。 Here is the code I was using before, a plus sign concatenating inside the require function instead of the template string. 这是我之前使用的代码,在require函数内部连接的加号而不是模板字符串。

{
  background: `url(${require('../../assets/' + edge.node.name.toLowerCase() + '.png')}) center no-repeat`
}

Would it be possible to define nested template strings? 是否可以定义嵌套模板字符串?

Yes, it's possible, but you had for some reason put the )}) part (that closes the require call, the interpolated value, and the CSS url ) in the wrong place: 是的,这是可能的,但是你出于某种原因把( )})部分(关闭了require调用,插值和CSS url )放在了错误的地方:

{
  background: `url(${require(`../../assets/${edge.node.name.toLowerCase()}.png`)}) center no-repeat`
//                                                                             ^^^
}

That said, it's probably a bad idea as it doesn't exactly make the code readable. 也就是说,这可能是一个坏主意,因为它并没有完全使代码可读。 Better use a variable: 更好地使用变量:

const bgurl = require(`../../assets/${edge.node.name.toLowerCase()}.png`);
… {
  background: `url(${bgurl}) center no-repeat`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM