Skip to content

Widget: Single Root Template

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

What are we learning here?

  • Each widget can replace its element with this.element.replaceWith()

Let's create a new widget which extends our previous widget, so we don't have to rewrite the whole base. The only change is the new function injectTemplate which will be overriden:

src/demo/apps/widget-basics-single-root/content.js

1
2
3
4
5
6
7
import BaseWidget from "../widget-basics/content.js";
export default class extends BaseWidget {
  myHeader = "JS Widget Single Root";
  injectTemplate(tpl) {
    this.element.replaceWith(`<div>${tpl}</div>`);
  }
}

You see here that we have used the function this.element.replaceWith() instead of this.element.html(). Furthermore we have sorround our origin template with a div using the template string <div>${tpl}</div>.

But why do we mention this here in a separate chapter? Isn't that a standard jQuery method?

No it is not. As already mentioned, the object this.element is very similar to a jQuery object, but it is not the same. For example, the replaceWith method we use here is not a jQuery method, but one defined by CodeCoupler. So it's quite possible that this doesn't work the same way as with the original jQuery method.

Let's create a new application in which we load our new widget:

src/demo/apps/single-root/index.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import { Application } from "@codecoupler/cc-ui";
import ChildComponent from "./content.js";
export default class extends Application {
  static defaults = {
    "@codecoupler": {
      panel: {
        panelSize: "640 400",
        headerTitle: "Test Single Root Template"
      }
    }
  };
  async start() {
    await this.stage.load(ChildComponent, { myWidgetArg1: "Value 1" });
  }
}

We load the new application in our system.js file (just by replacing the previous one):

src/system.js

1
2
3
4
5
6
7
import { Component } from "@codecoupler/cc-ui";
import TestApp from "./demo/apps/single-root";
export default class extends Component {
  async boot() {
    await this.stage.load(TestApp);
  }
}