Template literals, also known as template literals, appeared in JavaScript in its ES6 version, providing a new method of declaring strings using inverted quotes, offering several new and improved possibilities.
About template literals
Template literals were introduced in the ES6 version of JavaScript, allowing strings to be declared using inverted-quote syntax:
const chain = `text of the chain`;
This method offers new possibilities compared to strings declared with standard single or double quotes. For example, using this syntax it is possible to deifnir strings on several lines, and you can also insert variables anywhere in the strings without having to concatenate several strings.
In addition, you can also create DSLs (Domain Specific Language) with embedded tags, just like in React or Styled Components. Don't worry if you don't understand what I'm talking about, we'll look at each of these features in detail below.
Inserting Variables
Inserting variables or expressions in the middle of strings is very easy with template literals. This is also called variable interpolation. To do this, simply use the syntax ${varaible} o ${expresión}
In this example we insert a variable into a string:
const web = 'mano';
const mychain = `Welcome to ${web}`;
You can also insert any expression, be it a function or an operation. In this example we insert a mathematical expression:
const operation = `The sum of 2 + 2 is ${2 + 2}`;
In this example we call a function and display one thing or another based on the result of the function:
const result = `The result is ${check() ? 'correct' : 'false'}`
Strings on multiple lines
With the old JavaScript strings, as they were before ES6, it is also possible to define multi-line strings at the editor level by using at the end of the line:
const chain = 'This is a multi-line string';
This allows you to define strings on multiple lines, but when rendered, you will only see them on one line. In the case of the example above, you will see the string This is a multi-line string on the screen, on a single line.
However, it is also possible to define them on two real lines using the line break character:
const chain = 'This is a n multi-line string';
In case you want what you type on the screen to be transferred to your output, you will have no choice but to combine the line break n with the character :
const chain = 'This is a n multi-line string';
However, template literals make it much easier to define multi-line strings, because once you start the string, just press ENTER to create a new line, which will be reflected both in your editor and in the final output:
const chain = 'This is a multi-line string';
You can define as many lines as you want:
const chain = `This is the first line of the chain, this is the second and this is the third.`;
However, you must be careful with the spaces and indentations in your editor, because if you define the following string:
const chain = `This is the first line of the chain, this is the second`;
What you will see on the screen is the following:
This is the first line of the chain, this is the second
What you can do to fix this is to leave the first line blank so you don't have to add spaces in the second line if you want to format the code:
const chain = ` This is the first line of the chain, this is the second`.trim();
As you can see we have also used the trim() function to remove the first line break.
Template tags
This is a feature that at first glance seems unimportant, but in reality it is used by lots of famous libraries such as GraphQL, Apollo or Styled Components. Let's see how it works. Actually I've always worked with JavaScript in another language, so I have no idea what to call them in English, so I'll say template tags, although it doesn't sound too good, to be honest.
Template tags are simply functions that are placed before the template literal, like this:
templatetag`literaltemplate ${2 + 2}`;
As you can see, we have added the templatetag function, which should correspond to a real function that we have defined:
function templatetag(literals, ...expressions)
{
// Function code
}
This function accepts two parameters; literals and expressions. Let's see what each of these parameters represents:
Literals: An array containing the different parts of the template literals; that is, the parts of the text string that separate the interpolated elements.
Expressions: Contains all the expressions, variables or elements that we have interpolated.
Let's propose the following example.
const chain = `the result of ${2 + 2} it's four`;
The literals in our example will be an array with two elements. The first element of the array will be the string the result of and the second element will be the string is four, including spaces. That is, the text strings that are delimited by the interpolated elements are included.
On the other hand, the expressions in our example will contain only one element, which will be the element 4, the result of 2 + 2.
As you can see, just like when using normal template literals, we do not specify a function. However, that doesn't mean that no function is executed, as by default a function will be assigned that interpolates variables and strings.
Let's now define a more complex example like the following, where the blue variable has the value '#00bed5' and the green variable has the value '#11b200':
const chain = `I will say that
heaven is ${blue}
and the grass ${green}
or so I think`;
In this example the literals will be an array whose first element will be:
`I will say that heaven is `
The second element, which includes the line break, will be:
` and the grass `
And finally the third element, also including the line break, will be:
` or so I think`
As for the expressions, in this case they are an array with the elements '#00bed5' and '#11b200'.
The function passed to that template literal can do any task with those parameters.
In the following example we are going to define a function or template tag that, as it usually happens when you don't assign any function, interleaves the expressions with the literals:
const result = interpolate`I have ${50}€`
Below is the interpolation function we could use, as an example:
function interpolate(literals, ...expressions)
{
let chain = ``;
for (const [i, exp] of expressions.entries()) {
chain += literals[i] + exp; }
chain += literals[literals.length - 1];
return chain;
}
As mentioned before, both GraphQL and Styled Components or Apollo use template tags.
In Styled Components, template tags are used to create CSS definitions of components. In the following example, the template tag would be the styled.h1 function:
const Title = styled.h1` font-size: 1.6em; text-align: center; color: #000; `;
In Apollo, template tags are used to define GraphQL query schemas. In the following example, the template tag would be the gql function:
const consult = gql`
query {
...
}
`
And that's it