Documentation

Best Practices for Using Fragment Configurations

When you are creating page fragments for your site with your own configurations, it’s your responsibility to use them in their HTML presentation safely and effectively. Here are some techniques that you can use to make your fragments more effective and robust.

Escape Configuration Text Values

Malicious code can be inserted into text field configurations, wreaking havoc for other fragment users. You must escape fragment text values to guard against cross-site scripting (XSS) attacks.

For generic cases, an HTML escape() method is available. See the HtmlUtil class for more information.

<div class="fragment_38816">
    "${htmlUtil.escape(configuration.text)}"
</div>

To prevent JavaScript attacks, such as setting an attribute or appending HTML children, use the Liferay.Util.escapeHTML() function:

function (fragmentElement, configuration) {
    const escapedValue = Liferay.Util.escapeHTML(configuration.text)
}

Use Lists for Repeated HTML Elements

Avoid repeatedly writing the same HTML elements for your fragment by using FreeMarker lists. You can use the values from the configuration options you have implemented to implement your list’s logic.

For example, you can iterate over a number of lines that is defined in a configuration (like this example select configuration), and then use this HTML to list the configured number of lines:

<div class="fragment_1">
    [#list 1..configuration.numberOfLines as index]
        <li>Line number: ${index}</li>
    [/#list]
</div>

If you have implemented a collection selector configuration, you can also list all of the titles in the configured collection, like this example:

<div class="fragment_310">
    <h1>
        List of Items:
    </h1>
    <ul>
        [#if collectionObjectList??]
            [#list collectionObjectList as item]
                <li>${item.title}</li>
            [/#list]
        [/#if]
    </ul>
</div>

See the official FreeMarker documentation for more information.

Additional Information