Sun Dial Menu
Template Literals
Menu Template Literals
 

Template Literals

The Template Literal is a way of applying a "short-hand" to your code. I was going to say "simplify" but if you don't know what it means it hardly simplifies things!

When you come across a Template Literal in someone elses code it is easy not to see the grave quote symbol [the backtick symbol] (see the example I show below). The MDN website explains this is far more detail than I do here, but I started this page as I thought it was pretty neat.

The addition of the $ (place holder) is as I say an addition to what a Template Literal is. The Template Literal is just a way of of embedding a string within your code.

I came across this when looking at Event Bubbling and Capture.

`Capturing: ${elem.tagName}`

The ${ } is a placeholder within the template.

Top

The code in the bubbling and capturing:

<script>
for(let elem of document.querySelectorAll('*')) 
 {
  elem.addEventListener("click", 
  e => alert(`Capturing: ${elem.tagName}`), true);
  elem.addEventListener("click", 
  e => alert(`Bubbling: ${elem.tagName}`));
 }
</script>

What MDN say:

" Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
They were called "template strings" in prior editions of the ES2015 specification. "

The placeholder:

" Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (${expression}). The expressions in the placeholders and the text between the backticks (` `) get passed to a function. "

Links

References:

  • Arrow Functions - https:// developer.mozilla.org /en-US/docs/Web/ JavaScript/Reference/ Functions/Arrow_functions
  • Template literals (Template strings) - https:// developer.mozilla.org /en-US/docs/Web/ JavaScript/Reference/ Template_literals
  • A guide to JavaScript Template Literals - https:// flaviocopes.com/ javascript-template-literals/
  • HTML Templates via JavaScript Template Literals - https:// css-tricks.com/html-templates-via- javascript-template-literals/

Site design by Tempusfugit Web Design -