Parts - flexible components for your pages

Contents

In this chapter, you’ll place two parts on a page: one that shows the details of a country, and one that lists its cities and can be configured by the editor.

The country part

Parts are the visual building blocks of a page. Like the Text component, parts are added to regions, but you write their rendering yourself.

Your app has a part that shows details from the Country content type. Like a page component, it consists of a descriptor, a controller, and a view. Parts are placed in the src/main/resources/site/parts/ folder:

src/main/resources/site/parts/country/country.xml
<part xmlns="urn:enonic:xp:model:1.0">
  <display-name>Country</display-name>
  <description>Show simple details of the country</description>
  <form/>
</part>
src/main/resources/site/parts/country/country.ts
import { Content } from '@enonic-types/core';
import type { Response } from '/index.d';

// @ts-expect-error no-types
import {render} from '/lib/thymeleaf';
import {getContent} from '/lib/xp/portal';

type ContentCountry = { description?: string, wikipedia?: string }

// Specify the view file to use
const VIEW = resolve('./country.html');

// Handle the GET request
export function get(): Response {

    // Get the country content as a JSON object
    const content = getContent<Content<ContentCountry>>();

    // Prepare the model object with the needed data from the content
    const model = {
        name: content.displayName,
        description: content.data?.description || "Missing description",
        wikipedia: content.data?.wikipedia
    }

    // Prepare the response object
    const response: Response = {
		body: render(VIEW, model)
	};

    return response;
}
src/main/resources/site/parts/country/country.html
<div>
    <ul>
        <li data-th-if="${description}" data-th-text="${description}">Nice city indeed</li>
        <li data-th-if="${wikipedia}">
            <a data-th-href="${wikipedia}">Wikipedia</a>
        </li>
    </ul>
</div>

Task: Add the country part

  1. Open the country page - In Content Studio, edit the country you added the region to in the previous chapter.

  2. Insert the part - Drag Part from the Components widget on the right-hand side into the region, and select Country in the list.

  3. Verify the result - The page should look something like this:

    The country part on the Columbia page, showing facts about the country
You can also manage the components on a page from the page component view. It shows the components as a tree, on the left-hand side or floating above the page editor.
The page component view, a tree structure for managing the components on a page

Configurable part

The City list part is slightly more advanced. It:

  • lists the cities within a country

  • shows an image of each city

  • lets the editor choose the image cropping format

The part is also included in your app:

src/main/resources/site/parts/city-list/city-list.xml
<part xmlns="urn:enonic:xp:model:1.0">
  <display-name>City list</display-name>
  <description>Show all cities in a country</description>
  <form>
    <input type="ComboBox" name="crop">
      <label>Image crop</label>
      <occurrences minimum="0" maximum="1"/>
      <config>
        <option value="ORIGINAL">Original</option>
        <option value="WIDESCREEN">Widescreen</option>
        <option value="SQUARE">Square</option>
      </config>
    </input>
  </form>
</part>
src/main/resources/site/parts/city-list/city-list.ts
import { Content, PartComponent } from '@enonic-types/core';
import type { Response } from '/index.d';

// @ts-expect-error no-types
import {render} from '/lib/thymeleaf';
import {query} from '/lib/xp/content';
import {getComponent, getContent, imageUrl, ImageUrlParams} from '/lib/xp/portal';

type PartDescriptor = "company.starter.myfirstsite:city-list"
type PartConfig = { crop: 'ORGINAL' | 'WIDESCREEN' | 'SQUARE' }
type ContentCity = { photo?: string, slogan?: string, population: string }

// Specify the view file to use
const VIEW = resolve('./city-list.html');

// Handle the GET request
export function get(): Response {

    // Get the part configuration for the map
    const config = getComponent<PartComponent<PartDescriptor, PartConfig>>().config;
    const countryPath = getContent()._path;

    // Get all child item cities's  
    const result = query<Content<ContentCity>>({
        start: 0,
        count: 100,
        contentTypes: [app.name + ':city'],
        query: "_path LIKE '/content" + countryPath + "/*'",
        sort: "modifiedTime DESC"
    });

    // Create a crop based on configuration
    const scale = getImageScale(config.crop)

    // Map results to cities
    const cities = (result.hits || []).map(item=> ({
        name: item.displayName,
        photo: item.data.photo && imageUrl({ id: item.data.photo, scale: scale }),
        caption: getCitySlogan(item.data.slogan,item.data.population)
    }));

    // Set the model object
    const model = {cities};

    // Server log to inspect the model object
    log.info('Model object %s', JSON.stringify(model, null, 4));

    // Prepare the response object
    const response: Response = {
		body: render(VIEW, model)
	};

    return response;
}

function getImageScale(crop: string = 'ORIGINAL'): ImageUrlParams['scale'] {
    if (crop == 'SQUARE') { 
        return 'square(1080)';
    }
    
    if (crop == 'WIDESCREEN') { 
        return 'block(1080,300)';
    }

    return 'width(1080)';
}

function getCitySlogan(slogan: string, population?: string): string {
    return [slogan, population ? 'population: ' + population : '']
        .filter(Boolean)
        .join(' - ');
}
src/main/resources/site/parts/city-list/city-list.html
<div class="cities" style="min-height:100px;">
    <h2>Cities</h2>
    <p data-th-if="${#lists.isEmpty(cities)}">No cities found</p>
    <div data-th-unless="${#lists.isEmpty(cities)}" class="city" data-th-each="city : ${cities}">
        <h3 data-th-text="${city.name}">Utopia</h3>
        <figure>
            <img data-th-if="${city.photo}" data-th-src="${city.photo}"/>
            <figcaption data-th-if="${city.caption}" data-th-text="${city.caption}">Best city every</figcaption>
        </figure>
        <br/>
    </div>
</div>

In the view, the th:if and th:unless attributes handle an empty list. If no cities are found, the template displays "No cities found". Otherwise, it loops through the cities and outputs the details of each one.

Task: Add and configure the city list

  1. Insert the part - Add a new part to the same region as before, and select City list in the list.

  2. Configure the part - With the part selected, change its settings in the panel on the right-hand side. For example, select Widescreen in the Image crop dropdown, and click Apply.

  3. Verify the result - The page lists the cities of the country, with images in the format you chose:

    The city list part on the Columbia page, configured to show widescreen images

Image service

Images are scaled and cropped in real time by the image service. The part controller uses the imageUrl() function to create a link to each image, with the desired size and cropping.

Logging

The City list controller also writes its model object to the log. Open a country page, then check the terminal where the sandbox is running to see what the controller passes to the view.

Summary

You’ve placed two parts on a page, and configured one of them from Content Studio. With parts, you build visual blocks that editors can combine and configure on their own.

To learn more about parts, visit the parts documentation.

Contents

Contents