100-days-of-code

The 100 days journal - Consistently Code in 100 Days

View project on GitHub

What is template?

it is usual to use the same structure of code again and again, so it is easier if we have a template. to make template, use the <template> tag.

Example :

<template id="custom-paragraph">
  <p>My paragraph</p>
</template>

this html element will not appear on the web. this view will not appear until we choose to display it on the page. how? the traditional method is using javascript

let template = document.getElementById("custom-paragraph");
let templateContent = template.content;
document.body.appendChild(templateContent);

A beetter way

the best practice to render template as a component is create a custom html component based on that template. we can do so by using javascript :

customElements.define(
  "my-paragraph",
  class extends HTMLElement {
    constructor() {
      super();
      let template = document.getElementById("custom-paragraph");
      let templateContent = template.content;

      const shadowRoot = this.attachShadow({ mode: "open" });
      shadowRoot.appendChild(templateContent.cloneNode(true));
    }
  },
);

after that, we can call the my-paragraph tag on our html files!

<my-paragraph></my-paragraph>

Slots

slots is a place where we can place our desired data/component/tags to render at the template. slot tags have a name atribute, and we can refer to that name when we want to render some data/component/tags to template at that slot. let say we have a template look like this :

<template id="custom-paragraph">
  <p><slot name="my-text">My default text</slot></p>
</template>
we can use this template by render it using javascript like [[#A beetter way before]], and call it at the thml files :
<my-paragraph>
  <span slot="my-text">Let's have some different text!</span>
</my-paragraph>

the code above state that we want to use the my-paragraph custom component that we render using javascript, and display a span element, then place it at the slot with the name parameter is my-text.


Reference