[HTML5] Build Flexible HTML with HTMLTemplates using Slots and Web Components

HTMLTemplates are part of the web components specification. In this lesson we will learn what are HTML templates, how to use them and how to use the powerful HTMLTemplates slots inside a web component.

 

<script>
    const templateString = `
    <div>Some text</div>
    <form>
        <input name="test"/>
    </form>
    <slot name="slot1"></slot>
    `;
    const template = document.createElement('template');
    template.innerHTML = templateString;
    class MyWebComponent extends HTMLElement {
        constructor() {
            super();
        }

        connectedCallback() {
            this.appendChild(template.content.cloneNode(true));
        }
    }
    window.customElements.define('custom-element', MyWebComponent);
</script>
<custom-element>
    <p slot="slot1">This is a slotted paragraph</p>
</custom-element>
<custom-element>
    <iframe slot="slot1" width="560" height="315" src="https://www.youtube.com/embed/Bv_5Zv5c-Ts" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</custom-element>

 

posted @ 2019-02-10 20:49  Zhentiw  阅读(159)  评论(0编辑  收藏  举报