Skip to content

HTML Templating with lit html

Andre Kless edited this page May 2, 2021 · 7 revisions

content is up-to-date for ccm v26.1.1

Since ccmjs v26 you can also specify HTML templates via lit-html.

Usually, a templates.mjs is stored in the resources folder of a component, via which the HTML templates can then be specified, for example, as follows:

/**
 * @overview HTML templates of ccmjs-based web component for ...
 * @author André Kless <[email protected]> 2021
 */

import { html, render } from 'https://esm.run/lit-html';
export { render };

/**
 * returns the main HTML template
 * @param {string} name - Name of the person being greeted.
 * @returns {TemplateResult} main HTML template
 */
export function main( name = "World" ) {
  return html`
    <div id="main">
      Hello, ${name}!
    </div>
  `;
}

... (more templates)

The templates are then integrated and used in the component as follows:

...
( () => {

  const component = {
    ...
    config: {
      ...
      "html": [ "ccm.load", "./resources/templates.mjs" ],
      ...
    },

    Instance: function () {
      ...
      this.start = async () => {
        ...
        this.html.render( this.html.main( "John" ), this.element );
        ...
      };
      ...
    }
  };
  ...
} )();

The data that are dynamically integrated into an HTML template are passed as parameters to the function that returns the HTML template. For example, the reference to the component instance can also be passed. To ensure that no principles are violated, only read access to the instance is allowed within a template function. The state of the component instance should not be changed. The behavior should also not be specified in a template function. Callbacks for certain events are to be passed as parameters and not to be defined within the template function.