Docs

Documentation versions (currently viewingVaadin 14)

You are viewing documentation for an older Vaadin version. View latest documentation

Using Sub-templates

A client-side template can include child templates that are defined in other files. 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 is 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.

In this section, we demonstrate how to create a parent LitElement template that includes a child LitElement template.

Example: TypeScript LitElement parent template.

import {LitElement, html} from 'lit-element';
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 below).

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 is child-template.

  • 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 {LitElement, html} from 'lit-element';

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 {
}

F54A9770-8CCB-45FB-BF03-799ECC4951C0