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 '@polymer/paper-input/paper-input.js';
import '@vaadin/button';
import '@vaadin/text-field';
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-worldis a valid tag name, buthelloworldis not.The imported dependencies are:
PolymerElement(from the Polymer library): this is the required superclass of all Polymer templates;vaadin-text-field,vaadin-buttonandpaper-inputcomponents;htmlfor 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
@Tagannotation 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
@JsModuleannotation binds the Java class to the hello-world.js template class by specifying the relative path to the JavaScript module in thefrontendfolder in the project root. You can import multiple JavaScript resources using the@JsModuleannotation, if needed.The
@NpmPackageannotation declares a dependency on thepaper-inputnpm package:@polymer/paper-input 3.0.2. This annotation can be used to declare a dependency on any npm package.