How to nest template strings in ES6?

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?

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.