Creating a part componentΒΆ

Creating a component is very similar to creating a page. We need a descriptor, a controller and a view. When they are done, we can add the part component to the page by using drag and drop in live edit.

Start by creating folders part/mypart, and add a part.xml descriptor. This is very similar to our page.xml, the only difference is that a part cannot contain any regions. We want this part to list our favorite things to do, so we will need to configure some input for the part. We will add a text input which can be repeated up to 5 times.

<part-component>
  <display-name>My favorite things</display-name>
  <config>
    <field-set name="things">
      <label>Things</label>
      <items>
        <input type="TextLine" name="thing">
          <label>Thing</label>
          <immutable>false</immutable>
          <indexed>true</indexed>
          <occurrences minimum="0" maximum="5"/>
        </input>
      </items>
    </field-set>
  </config>
</part-component>

Next, create a controller inside the same folder, controller.js.

exports.get = function(portal) {

  // Find the current component from request
  var component = execute('portal.getComponent');

  // Find a config variable for the component
  var things = component.config["thing"] || [];

  // Define the model
  var model = {
    component: component,
    things: things
  };

  // Resolve the view
  var view = resolve('/cms/view/my-favorite-things.html');

  // Render a thymeleaf template
  var body = execute('thymeleaf.render', {
    view: view,
    model: model
  });

  // Return the result
  return {
    body: body,
    contentType: 'text/html'
  };

};

The part needs a root element with the attribute data-portal-component-type. In this case, it will be a part, but we can also resolve it dynamically as explained in the example. The things parameter is basically just JSON data, and we can loop it easily in Thymeleaf and print its value.

<section data-th-attr="data-portal-component-type=${component.type}">
  <h2>A list of my favorite things</h2>
  <ul class="item" data-th-each="thing : ${things}">
    <li data-th-text="${thing}">A thing will appear here.</li>
  </ul>
</section>

The part can now be added to the page via drag and drop. You will be able to configure the part in the context window on the right side of live edit. Here is an image of the result.

../../_images/my-part.png