Skip to content

Widgets: Single Root Template

We would now like to highlight a few rare aspects. The first one is using a HTML template with a single root.

As you have seen we have used before an HTML file where we have defined the inner structure of oour widget. Some times the HTML template have to be a single root template. This means that the template has only one HTML element in the root.

Let's start creating a new file in the same folder of our widget. As it is mostly the same as index.ejs.html we will use here the include statement of the EJS parser and sourround the content with a div:

src/widgets/testing-features/single-root.ejs.html

1
<div><%- include index.ejs.html %></div>

Now we create a new widget which extends our previous widget. The only change is the new function buildStructure which will be overriden:

src/widgets/testing-features/single-root.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import BaseWidget from "./index.js";
import template from "./single-root.ejs.html";
import $ from "jquery";
export default class extends BaseWidget {
  myHeader = "JS Widget Single Root";
  buildStructure() {
    let $template = $(
      template({
        myTemplateArg: `(Arg1: ${this.options.myWidgetArg1}, Arg2: ${this.options.myWidgetArg2})`,
      })
    );
    this.env.$element.replaceWith($template);
    this.env.$element = $template;
    this.env.element = $template.get(0);
  }
}

You see here that we have used the jQuery function replaceWith instead of html. The second thing you have to pay attention is the redefinition of this.env.$element and this.env.element. This have to be done because the origin element was removed and any following functions assume that the element can be found there.

Let's use the new widget in our application:

src/apps/first-app/index.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { Application } from "@codecoupler/cc-ui";
import TestingWidget from "../../widgets/testing-features/single-root.js";
export default class extends Application {
  async init() {
    return {
      panelSize: "500 400",
      headerTitle: "My First Title"
    };
  }
  async start() {
    this.widget(TestingWidget);
  }
}