AEM data-sly-template

data-sly-template use to create a template or reusable html code which can be consume on multiple places by data-sly-call.

Using this approach we can easily include one html into another and pass data in the form of parameter.

Example

Let’s create an AEM component beneath highlighted components hierarchy as part of current implementation:

Please follow below steps to create a component and consume data-sly-template and data-sly-call in AEM:

  1. Navigate to ui.apps/src/main/content/jcr_root/apps/practice/components folder and create a custom folder. In our case or for current tutorial it is practice.

2. Create file .content.xml beneath practice folder created in first step and paste below content:

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0"
xmlns:cq="http://www.day.com/jcr/cq/1.0"
xmlns:jcr="http://www.jcp.org/jcr/1.0"
jcr:primaryType="cq:Component"
jcr:title="Practice"
componentGroup="Practice"/>

jcr:primaryType is to create a node of type cq:component.

jcr:title is to declare component title.

componentGroup is use to group component under one category.

3. Create a pratice-template.html file and paste below code having <template> tag and data-sly-template block:

<template data-sly-template.include="${@ categories, mode}">
<div> Categories = ${categories} </div>
<div> mode = ${mode} </div>
</template>

data-sly-template allows us to create template and declare parameters expecting when template gets call.

4. Create a pratice.html file to consume template and paste below code having data-sly-call Sightly block:

<sly data-sly-use.temp="${'practice-template.html'}" data-sly-call="${temp.include @ categories='category_1', mode='js'}"/>

5. Below is the over all picture for creation of template and call same template:

6. Create page, drag and drop practice component on the page. Click on Drag components here option as shown below:

7. Select Practice component option as highlighted below:

8. After successful component drag and drop will show below output:

Note: We can pass Java variables and objects as a parameter to template as shown below.

<sly data-sly-use.temp="${'practice-template.html'}" data-sly-call="${temp.include @ categories=properties.title, mode=use.modelObj}"/>

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0