HTML <template> Element versus Javascript Template Literals
Asked Answered
S

1

8

Mozilla says Web components consist of three main technologies:

  1. Custom elements
  2. Shadow DOM
  3. HTML templates

Is number 3, "HTML templates", even necessary in light of ECMAscript's Template Literals?

Look at this example I got from James Milner:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Web Component</title>
    <script type="text/javascript">
    // We define an ES6 class that extends HTMLElement
    class CounterElement extends HTMLElement{
            constructor() {
                    super();
                    // Initialise the counter value
                    this.counter = 0;

                    // We attach an open shadow root to the custom element
                    const shadowRoot= this.attachShadow({mode: 'open'});

                    // We define some inline styles using a template string
                    const styles=`
                            :host {
                                    position: relative;
                                    font-family: sans-serif;
                            }

                            #counter-increment, #counter-decrement {
                                    width: 60px;
                                    height: 30px;
                                    margin: 20px;
                                    background: none;
                                    border: 1px solid black;
                            }

                            #counter-value {
                                    font-weight: bold;
                            }
                    `;

                    // We provide the shadow root with some HTML
                    shadowRoot.innerHTML = `
                            <style>${styles}</style>
                            <h3>Counter</h3>
                            <slot name='counter-content'>Button</slot>
                            <button id='counter-increment'> - </button>
                            <span id='counter-value'> 0 </span>
                            <button id='counter-decrement'> + </button>
                    `;

                    // We can query the shadow root for internal elements
                    // in this case the button
                    this.incrementButton = this.shadowRoot.querySelector('#counter-increment');
                    this.decrementButton = this.shadowRoot.querySelector('#counter-decrement');
                    this.counterValue = this.shadowRoot.querySelector('#counter-value');

                    // We can bind an event which references one of the class methods
                    this.incrementButton.addEventListener("click", this.decrement.bind(this));
                    this.decrementButton.addEventListener("click", this.increment.bind(this));

            }
            increment() {
                    this.counter++
                    this.invalidate();
            }
            decrement() {
                    this.counter--
                    this.invalidate();
            }
            // Call when the counter changes value
            invalidate() {
                    this.counterValue.innerHTML = this.counter;
            }
    }
    // This is where the actual element is defined for use in the DOM
    customElements.define('counter-element', CounterElement);
    </script>
</head>
<body>
    <counter-element></counter-element>
</body>
</html>

Notice how he doesn't use an HTML template, but instead uses an ecmascript template literal to set the innerHTML of the shadowRoot.

After this, he uses querySelector to get internal elements of the shadowRoot and he ultimately adds event listeners to the increment and decrement buttons.

If you were to use a HTML template, instead of an ecmascript template literal, what does this gain you?

Conceptually, I'm struggling to find a situation where I'd prefer an HTML Template Element over an Ecmascript Template Literal.

Please advise.

Serve answered 15/11, 2018 at 2:41 Comment(10)
Another issue is that template literals can be transpiled easily (and with Babel and polyfills, which any serious project will have, the project will work in IE), while <template> elements appear to be not supported in IEDevinna
A counter argument is for keeping your HTML as HTML, separation of concerns and all that. If you want to change your document structure, change your HTML document, not javascript. That is more intuitive for me . The lack of IE support for templates does indeed suck. There is a kind of workaround by using <script type="text/template" id="postTemplate"> in place of <template>. For an example with jquery see: #52377027 . jQuery isn't actually required it's just first of my examples that I found.Inhesion
"Separation of concerns" has its place in general web page development. However, one of my favorite aspects of web components is that you can encapsulate all concerns (structure, style, and behavior) in one place. This simplifies reuse.Serve
Possible duplicate of Template html and template string in web componentsSeringapatam
Template literals are a JS syntactic sugar thing and have nothing to do with HTML functionality.Keynes
@Keynes Yes, but html can be placed into template literals and be a spec-standard way of replacing JSX. That's done in projects like lit html and hyperHTML.Serve
@LonnieBest But neither of those has anything to do with web components or html <template>s, which is what this question is asking aboutKeynes
@Keynes When you are dynamically generating the html that ultimately lands into the rendered web component, both <template> and template literals can be the store-house where the non-dynamic aspects of that html are stored. Keep in mind, that the <template> itself can be dynamically generated and used by a web component. Or you can store that static html in a template literal instead. My end goal is to have portable components where everything is contain in one javascript file and the question was asked with this goal in mind.Serve
@LonnieBest if you dynamically generate the <template> element, you're still using that part of the web components technology? No, template literals are not a "store-house", they are js syntax. You can achieve exactly the same using plain string literals, or load/generate the strings from elsewhere.Keynes
@Keynes Sometimes syntax alone is a huge step forward. It can change what you're willing to do. It's nice when you can just copy and paste a multi-line, formatted string right into your code and it still looks the same and is easy to edit.Serve
S
3

The template tag is not 'required' for Web Components per se. It probably made more sense when HTML Imports were being pushed, allowing for importing and reusing HTML snippets, but that has since ceased. Here you could have imported a template and reused that.

It's important to note the specifications are designed to be standalone and can be used interdependently of each other also, which makes them versatile. The HTML tag has use cases outside of the realm of Web Components; it's useful because it allows you to define a piece of markup that doesn't render until instantiated via JavaScript later on. Indeed you can use templates without using any of the other specifications (Custom Elements, Shadow DOM etc).

The template tag can certainly be used in conjunction with the other specs. For example, we could have used it in the example shown to arguably make the code less imperative and more markup focused like so:

 <template id="counterTemplate">
   <style>
         :host {
             position: relative;
             font-family: sans-serif;
         }

         #counter-increment, #counter-decrement {
             width: 60px;
             height: 30px;
             margin: 20px;
             background: none;
             border: 1px solid black;
          }

         #counter-value {
             font-weight: bold;
         }
   </style>
   <h3>Counter</h3>
   <slot name='counter-content'>Button</slot>
   <button id='counter-increment'> - </button>
   <span id='counter-value'> 0 </span>
   <button id='counter-decrement'> + </button>
</template>

And then use this later in JavaScript like so:

   const template = document.querySelector('#counterTemplate');
   const counter = document.cloneNode(template);
   shadowRoot.appendChild(counter);

The downside here is that it would require that the template existed in the DOM prior to the instantiation as it is relying on the #counterTemplate template being there. In some ways this makes the Custom Element less portable, hence why template literal might be more desirable. I haven't tested the performance of both, but my gut tells me that the template would possibly be more performant.

Disclaimer: I wrote the original blog post

Selfevident answered 15/11, 2018 at 11:1 Comment(3)
Indeed, it would make portability more burdensome.Serve
Another topic, I haven't found information on is memory consumption when placing style in a shadow root.Serve
I found one interesting video explaining ES6 template literals here : youtube.com/watch?v=asRu9MPojFEEberle

© 2022 - 2024 — McMap. All rights reserved.