What and Why?
Template Literal is introduced in ES6, It is a new way to create a string. It allows us more control over dynamic strings (Interpolate and expressions) in our programs.
Template Literal of a single line. Code Pen
Use backticks instead of a single or double quote
Template Literal of multiple lines
Use a backtick instead of a single or double quote and use \n \ to make your space.
Interpolate using the `${…}` syntax:
Interpolate the variable of dynamic string using the syntax `${…}`.
Expression using the syntax `${…}` :
The expression passed into the syntax `${…}` allows us to take any valid JavaScript expression to find the result value when it needed for inline Maths.
Tagged Template: Code Pen
It means to execute a template using a function. No parentheses required to call the function. Just tag the argument near the function name.
In the example below, the method templateTag returns a literal and the method is getting called in var profile with an argument (String Literal).
In the Function definition, the first argument is an array holding the entire string. Split it where ever there is expression or interpolation is placed ${} in the literal.
The second argument of the method is all the dynamic values that we applied in the string literal
args = [“I am ”, “ ”, “ working as ”, “ ”]
…dynamicValues = Alice, Thomas, Application Developer [Rest Operator used]Now see the return statement, how it is reconstructed again with dynamic values.
Why Tagged Template?
Above we saw how to use the tagged template, let's see the answer for Why?
The tagged template is used as a container to holds some hidden content from the user when the page loads. In the example above, the profile holds some data before the JavaScript calls “I am “ ” working as “ ” ”
The hidden content can be rendered later with JavaScript. Same here the method templateTag helps to render the dynamic values.
When Tagged Template?
You can use, whenever the content is reused again and again. eg) In an application, all over the pages using the button with similar CSS, maybe the button name will differ. In such cases, this will helps.
Hope it will give a basic view of the Template Literals & Tagged templates, Please write your questions for any doubts or corrections.
Let’s discuss the next feature of ES6 in the next story.
Next topic: Class in JavaScript & OOPS Concept