[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>

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10360218.html