Creating a Simple Component Using the Polymer Template API

Polymer templates are deprecated. Lit templates are recommended instead.

Creating the Template File on the Client Side

The first step is to create the Polymer JavaScript template file on the client side in frontend/src/hello-world.js. This file contains the view structure.

Example: Creating the hello-world.js JavaScript Polymer template file.

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@vaadin/vaadin-text-field/vaadin-text-field.js';
import '@vaadin/vaadin-button/vaadin-button.js';
import '@polymer/paper-input/paper-input.js';

class HelloWorld extends PolymerElement {

    static get template() {
        return html`
            <div>
                <vaadin-text-field id="firstInput"></vaadin-text-field>
                <paper-input id="secondInput"></paper-input>
                <vaadin-button id="helloButton">Click me!</vaadin-button>
            </div>`;
    }

    static get is() {
          return 'hello-world';
    }
}

customElements.define(HelloWorld.is, HelloWorld);
  • This is the JavaScript ES6 module that defines a Polymer template.

  • The is() function defines the name of the HTML tag that is used to reference this module. The tag name should contain at least one dash (-). For example, hello-world is a valid tag name, but helloworld is not.

  • The imported dependencies are:

    • PolymerElement (from the Polymer library): This is the required superclass of all Polymer templates.

    • vaadin-text-field, vaadin-button and paper-input components.

    • html for inline DOM templating.

Creating the Java Template Class

To use the client-side Polymer template on the server side, you need to create an associated Java class that extends the PolymerTemplate class.

Example: Creating the HelloWorld Java template class.

@Tag("hello-world")
@NpmPackage(value = "@polymer/paper-input", version = "3.0.2")
@JsModule("./src/hello-world.js")
public class HelloWorld extends PolymerTemplate<HelloWorld.HelloWorldModel> {

    /**
     * Creates the hello world template.
     */
    public HelloWorld() {
    }

    public interface HelloWorldModel extends TemplateModel {
    }
}
  • The @Tag annotation name matches the return value of the is() function (static getter) in the JavaScript template. This ensures that the tag name is the same on the server and the client.

  • The @JsModule annotation binds the Java class to the hello-world.js template class by specifying the relative path to the JavaScript module in the frontend folder in the project root. You can import multiple JavaScript resources using the @JsModule annotation, if needed.

  • The @NpmPackage annotation declares a dependency to the paper-input npm package: @polymer/paper-input 3.0.2. This annotation can be used to declare a dependency to any npm package.