Tuesday 26 July 2016

AEM Sightly Templates

When repetitive code is used within an html page, such as capturing an address, using a Sightly Template is really useful to avoid unnecessary duplication and improve maintenance.

Template

The template can be created at the top of the page as

    <template data-sly-template.address> 
        <div class="address">
            Street:  <input type="text" name="street">
            <br>
            Town: <input type="text" name="town">
            <br>
            Postcode: <input type="text" name="postcode">
        </div>
    </template>

Usage

The template usage is very straight forward.  Simply use the Sightly 'call' function,

    <div data-sly-call="${address}"></div>

Separate File

As templates get bigger or for maintainability a separate file can be used.  AEM will do the work of gathering the template files together for a given page so there is no problem about the paths in AEM being available.

To use a separate file the template must be imported in the html page and then called with the extra selector which defines the file it lives in

address.html
    <template data-sly-template.address> 
        <div class="address">
            Street:  <input type="text" name="street">
            <br>
            Town: <input type="text" name="town">
            <br>
            Postcode: <input type="text" name="postcode">
        </div>
    </template>

Import
Import the template file

    <div data-sly-use.details="address.html"></div>

Use
The usage changes very slightly as it has to reference the import ('details') as well as the template ('address') within the file.

    <div data-sly-call="${details.address}"></div>

Using Parameters

Parameters can also be used within a template.  This is useful if you want the template to behave a particular way or if you want to name the fields slightly differently for each instance of the template.


    <template data-sly-template.address="${@ instance}"> 
        <div class="address">
            Street:  <input type="text" name="${instance}Street">
            <br>
            Town: <input type="text" name="${instance}Town">
            <br>
            Postcode: <input type="text" name="${instance}Postcode">
        </div>
    </template>

Here the instance of the template is passed in so that each of the fields can have a unique name even if the template is used multiple times.  In the example below the Invoice address and Delivery address can have different instances and therefore different names for the fields.


    <div data-sly-call="${details.address @ instance='InvoiceAddress'}"></div>

    <div data-sly-call="${details.address @ instance='DeliveryAddress'}"></div>
This usage of sightly to generate templates can be very useful.

No comments:

Post a Comment