How to nest template strings in ES6?

六月ゝ 毕业季﹏ 提交于 2019-12-19 05:15:07

问题


I got an prefer-template error from eslint. 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:

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

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

Would it be possible to define nested template strings?


回答1:


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:

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


来源:https://stackoverflow.com/questions/36028061/how-to-nest-template-strings-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!