March 28, 2020
Estimated Post Reading Time ~

Working with Sightly and Templates in AEM 6.1

Working with Sightly and Templates in AEM 6.1















Use templates in AEM 6.1 Sightly :
1. Template (data-sly-template)

These are the HTML blocks that act as a function. Every block will have an identifier and as a normal function, they do accept parameters. When you are defining the block, you can define all parameters that will be accepted by it.

Example1:
<template data-sly-template.first>
This is my first Template.
</template>

Now, create a simple template with the identifier as ‘first‘.

In order to use this block you call them with an identifier

2. Call (data-sly-call)
The call will help you to get a declared HTML block or template.
<div data-sly-call="${first}"></div>

The above statement will call our template with the identifier ‘first‘.

Output HTML:
<div>
This is my first Template.
</div>


Example 2:
Passing parameters to templates

Template: <template data-sly-template.second="${@ x, y, z}">
Value of x = ${x}, y= ${y}, z= ${z}
</template>


Call:
<div data-sly-call=”${second @ x=1, y=2, z=3}”></div>

Output HTML:
<div>
Value of x = 1, y= 2, z= 3
</div>


Example 3:
Template in different file

The above examples are based on assumptions that templates are present in the same file in which we are calling them, other many scenarios when you create a template in one HTML and need to call them in different files.

Template:
It will be presented on a path
/apps/project/component/content/sightly-demo/mytemplates.html

<template data-sly-template.third="${@ x, y, z}" >
Value of x= ${x}, y= ${y}, z= ${z}
</template>


Call:
The file in which we will call this is present at path /apps/project/component/content/sightly-demo/sightly-demo.html

<div data-sly-use.data="mytemplates.html" data-sly-call="${data.third @ x=1, y=2, z=3}">
</div>


You can use “data-sly-use” which will help you to get a reference to the file.
A path to the file can be absolute or relative.

Output:
<div>
Value of x = 1, y= 2, z= 3
</div>

One more example where our template will call sightly JS file before returning HTML.

Example 4:
<template data-sly-template.fourth="${@ page}" data-sly- use.tmpl="${'simple.js' @ page=page, descriptionLength=50}">
<h1>${tmpl.title}</h1>
<p>${tmpl.description}</p>
</template>


simple.js
use(function () {
var Constants = {
DESCRIPTION_PROP: "jcr:description"
};


var title = this.page.getNavigationTitle() || this.page.getTitle() || this.page.getName();
var description = this.page.getProperties().get(Constants.DESCRIPTION_PROP, "").substr(0, this.descriptionLength);
return {
title: title,
description: description
};
});


Call: 
<div data-sly-use.tmpl="mytemplates.html" data-sly-call="${tmpl.fourth @ page=currentPage}">
</div>

Output:
<div>
<h1>English</h1>
<p>This is a demo page. It shows how to use templates</p>
</div>



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.