Displaying contentΒΆ

Now that a content-type has been defined and a content created, a new component part is needed to display the content. But first, a person content should be prepared in a specific location so that the code below can be copy/pasted and work properly. In the admin console content manager app, right-click on the my-first-site and select new. Then choose folder and name it People. Next, create a new person content in the People folder with the first name Edvard and the last name Munch and type in anything you like for the bio. Upload any image for the picture. Notice the path of this content under the display name is /my-first-site/people/edvard-munch.

Now create a new folder in your project under the parts folder and name it person-show. Now create a part descriptor file named part.xml. This descriptor only needs a display-name for now.

<part-component>
  <display-name>Person</display-name>
  <config/>
</part-component>

Next, create the person-show controller named controller.js.

exports.get = function(req) {

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

  // Find the right content
  var person = execute('content.get', {
    key: '/my-first-site/people/edvard-munch'
  });

  // Combine the first and last name
  var personName = [
    person.data['first-name'],
    person.data['last-name']
  ].join(' ').trim();

  // Retrieve the image ID from the content used to create a image URL
  var imageId = person.data['image'];

  // Create a URL to the image
  var imageUrl = execute('portal.imageUrl', {
    id: imageId,
    filter: 'scaleblock(400,400)'
  });

  // Create view model
  var model = {
    component: component,
    person: {
      name: personName,
      image: imageUrl,
      bio: person.data['bio']
    }
  };

  // Return the result
  return {
    body: execute('thymeleaf.render', {
      view: resolve('person-show.html'),
      model: model
    }),
    contentType: 'text/html'
  }

};

Now a simple view file called person-show.html can be created to render the content data that is passed from the controller.

<div data-th-attr="data-portal-component-type=${component.type}">
  <p>
    <img class="img-responsive img-circle" data-th-src="${person.image}"
      src="../assets/images/person.jpg" alt="" />
  </p>
  <h3 data-th-text="${person.name}" data-th-remove="tag">Jane Doe</h3>
  <p data-th-text="${person.bio}">Person bio</p>
</div>

Rebuild the project and add the Person part to the page in live edit. This is a very simple example and not a very practical way to retrieve content. Errors would occur if the content name changed (due to the hardcoded content path), or if any of the content fields were missing values. The descriptor and controller will be modified in the next step to use a relationship type that will make the code more dynamic and robust.