Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 799
lvarayut Avatar asked Mar 16 '16 06:03

lvarayut


People also ask

Can you nest template literals?

Nesting together multiple template literals can create unnecessary complexity, which reduces the code quality. The code becomes less readable and can cause maintainability issues overtime. A better practice, in these situations, is to move the nested template into a separate statement.

What are ES6 template strings?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.

What is `` in JS?

Backticks ( ` ) are used to define template literals. Template literals are a new feature in ECMAScript 6 to make working with strings easier. Features: we can interpolate any kind of expression in the template literals. They can be multi-line.

What is string interpolation in ES6?

String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.


Video Answer


1 Answers

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`
}
like image 173
Bergi Avatar answered Oct 17 '22 14:10

Bergi