Skip to main content

Templates

Component System

The Cog library uses Web Components to create reusable HTML templates. These templates are defined using the <template> HTML element and can contain any HTML markup, including placeholders for dynamic content. When a custom element is used in the HTML, Cog replaces it with the corresponding template's content. This allows you to define a template once and use it multiple times with different data, making your HTML more maintainable.

How Templates Work

In the next example, there are two templates defined: my-element and my-checkbox.

<template id="my-text">
<div class="bold">{{ children }}</div>
</template>
<template id="my-checkbox">
<label><input type="checkbox" /> {{ dataLabel }}</label>
</template>

Each template has an id which is used to reference it in the rest of the HTML. Inside the templates, you can see {{ children }} and {{ dataLabel }}. These are placeholders for dynamic content.

Template must have a single child element!

When a custom element like <my-text> or <my-checkbox> is used in the HTML, Cog replaces the custom element with the corresponding template's content. Any placeholders in the template are replaced with the corresponding data from the custom element.

This
<my-text>I'm the child</my-text>
<my-checkbox data-label="Check it"></my-checkbox>

For example, in the line <my-text>I'm the child</my-text>, I'm the child replaces {{ children }} in the my-text template.

In the case of <my-checkbox data-label="Check it"></my-checkbox>, the data-label attribute provides the data for the {{ dataLabel }} placeholder in the my-checkbox template.

This way, you can define a template once and then use it multiple times with different data, reducing repetition and making your HTML more maintainable.

Custom attributes as props

Custom data attributes (prefixed with data-) can be used to pass additional data to the template. Cog converts these attribute names to camelCase and makes them available as variables inside the template.

<!-- Definition -->
<template id="my-checkbox">
<label>
<input type="checkbox" data-attribute-checked="{{ dataIsChecked }}" />
{{ dataLabel }}
</label>
</template>

<!-- Usage -->
<my-checkbox data-label="Check it" data-is-checked="true"></my-checkbox>

Local Component State

Using the variable() method we can scope the reactive variables to specific templates.

const count = variable("count", 0, "my-counter");
const increment = variable("increment", () => count++, "my-counter");

We can use local count and increment in Template like this:

<template id="my-counter">
<button data-on-click="increment()">Count is {{ count }}</button>
</template>

Here, we're using Cog's data-on-click attribute, read more about it in the Event Handlers section.