Documentation

Documentation versions (currently viewingVaadin 23)

You are viewing documentation for Vaadin 23. View latest documentation

Using Sub-Templates

A client-side template can include child templates that are defined in other files. A LitElement template is used in the examples below, but Polymer templates are also supported.

You can use the tag name and import function to reference the child template. It’s also necessary to let the server know how to load the child file. This happens automatically if you bind the child template in the mapped Java template file, using the @Id annotation, in the same way as any other component.

This section demonstrates how to create a parent LitElement template that includes a child LitElement template.

Example: TypeScript LitElement parent template.

import { html, LitElement } from 'lit';
import 'child-template.js';

class ParentTemplate extends LitElement {
  render() {
    return html`
      <div>Parent Template</div>
      <child-template id="childTemplate"></child-template>
    `;
  }
}

customElements.define('parent-template', ParentTemplate);
  • The TypeScript LitElement uses a child-template element. This is a custom element defined in child-template.ts (see later in this article).

Example: Mapped parent template Java class.

@Tag("parent-template")
@JsModule("./com/example/parent-template.ts")
public class ParentTemplate extends LitTemplate {

    @Id("childTemplate")
    private ChildTemplate child;
}
  • The associated Java template file defines that ChildTemplate should be instantiated for any template element with a matching tag name, that’s child-template.

  • An instance of ChildTemplate must be created on the server. The @Id annotation mapping ensures that this instance is automatically created and wired to the <child-template> element in the parent template.

Example: TypeScript LitElement child template.

import { html, LitElement } from 'lit';

class ChildTemplate extends LitElement {
  render() {
    return html`<button>Child Template</button>`;
  }
}

customElements.define('child-template', ChildTemplate);

Example: Mapped child template Java class.

@Tag("child-template")
@JsModule("./com/example/child-template.ts")
public class ChildTemplate extends LitTemplate {
}

ED0B29C0-0EA2-4809-802B-82888B4068B1