Creating & Rendering

To create a template you will need to use the html core API and it is straight forward to use.

import {html} from "@beforesemicolon/markup";

html`<h1>Hello Worls</h1>`;

The html is a tagged template, function which is a special way to create template literals. Inside you can place any valid HTML and it will be handled accordingly.

This is not a pattern specific to Markup. It is pure JavaScript. Template literals allow you to create templates in an elegant and simple way, and it is a capability that makes this library possible.

How it works?

When you define a template, nothing happens. No parsing, no evaluation of any kind. This means that you can create a lot of these templates and have it waiting as properties, variable, and return values. Like a true first class citizen.

When you create a template you get a HTMLTemplate instance which we will explore throughout these documents.

Rendering

Everything starts with the rendering, and it happens via the render method from the HTMLTemplate instance.

const temp = html`<h1>Hello Worls</h1>`;

temp.render(document.body)

The render method accepts a DOM element where the template should be rendered. It is only when the render is call that the template is parsed to HTML Elements.

The rendering happens only ONCE. If you call the render method repeatedly only the first call will actually render content.

For whatever reason, if you really want to force a re-render, you can specify the second argument value of true to force a re-render.

temp.render(document.body)
temp.render(document.body, true) // forces re-render

Understanding rendering

One thing to remember is that the html returns a HTMLTemplate instance which contains unique instances of every Node. Essentially it works like a Node meaning, the same instance cannot be in 2 places on the document at once.

If you render a template in a place in the DOM, then try to render it in a different place, it will be automatically removed from the previous place.