Slings Model and HTL (Sightly) | Slings Model and HTL In AEM

Hello Coders, In this article you are going to learn about Sling Models and HTL in AEM. At the end of this article, you are ready to implement and to answer these questions:

  • What is Sling Model ?
  • Why Sling model is Used in AEM ?
  • How to Create Sling Models in AEM?
  • What is HTL ?
  • Why we use HTL (Sightly) in AEM ?
  • How to use HTL in HTML pages in AEM?

Sling Models | Sling Model In AEM

What is Sling Model ?

Basically, Sling Models are annotation driven Java “POJO’s” (Plain Old Java Objects) that facilitate the mapping of data from the JCR to Java variables, and provide a number of other niceties when developing in the context of AEM.

So, Sling Models are “pure” POJOs which maps Sling objects (resources, request objects etc.). Since Sling Models are annotation-driven Plain Old Java Objects (POJOs), so annotations are used a lot. They allow you to map resource properties, assign default values, inject OSGi services and much more.

To understand Sling, first we need to know architecture of AEM Sling Framework.

In the above picture we have designed a complete layer architecture to show where we use Sling model and HTL.

So here you can take example, Business Logic Layer is your Sling Model and Presentation Layer is your HTL to show the data which comes from Sling model.

Some Annotation of Apache Sling:

@Model : declares a model class or interface

@Inject : marks a field or method as injectable

@ValueMapValue : is an injector specific annotation that will specifically pick value from valuemap injector. It is equivalent to @Inject @Source("valuemap")

@Named : declare a name for the injection (otherwise, defaults based on field or method name).

@Optional : marks a field or method injection as optional

@Source : explictly tie an injected field or method to a particular injector (by name). Can also be on other annotations.

@Filter : an OSGi service filter

@PostConstruct : methods to call upon model option creation (only for model classes)

@Via : change the adaptable as the source of the injection

@Default : set default values for a field or method

@Path : only used together with the resource-path injector to specify the path of a resource

@PostConstruct: declares the function which would initialize the bean after deriving information based on business logic. The function is called after the all injections have completed.

For more list click here

————-Most Important thing to know————-

Now, to understand Sling model and HTL more, you need to know that where exactly data stored after we authored any component.

Let’s understand, So when we click done for any component after input field, all data is saved in JCR for that particular page.

again, when you click on developer mode and click on particular component then you will find where exactly our data is saved after Done button click.

Step to follow to see your JCR data————–

1) Click on developer mode, which is mentioned in your page right side Edit Button

2) Click on component, In my case component is : Demo Sling Htl and click first one to see where actually your JRC is stored.

Click on the Content Path Url

Now you will see your JCR and how your data is stored

Now you will confused that what is myname, So myname is the name which is written in cq dialog to identify the field input and data.

To see that, your need to go back to 2 step, see image and click on second marked circle. You will see the details.

Now you are understand that where our JCR are, and what are the formats.

Why Sling model is Used in AEM ?

Again, come to our topic that is Sling model, What Sling model do here is just take this data and map it in java variables, as we know that Sling model is annotation based model so we only need to import that annotation in our code and that annotation will do rest of the work, these are the reason that we are use Sling in AEM.

also read:

How to Create Custom AEM Component ?

How to Create Policy In AEM ?

How to Set Up AEM Environment for Development ?

How to Create Sling Models in AEM?

1) Create a file under core/src/main/java/com/aem/wknd/models

We need to create .java file under this folder and make the name as what your component name is, so that you can identify which model is written for what component. In my example I have named component : demoslinghtl

So, my created file will be : DemoSlingHtl.java

2) Create Model with model annotation and code

Suppose I have one data in JCR and name is myname, so our code will be,

package com.adobe.aem.guides.wknd.core.models;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class DemoSlingHtl {

    @ValueMapValue
    private String myname;

    public String getMydetails() {
        return myname;
    }
}
i) Here, @Model annotation describe that DemoSlingHtl is a Sling model class.

In @Model(adaptables = Resource.class), adaptables = Resource.class this class is passed because the Resource.class tell that which resource need to map and what will be adaptable.

When we call from the HTL then that will be resources for respective model, and you can see these classes in your Adobe Experience Manager Web Console – Sling Adapters or see below pictures.

Aahhaa 🤔, Confused in Adaptable and adapter ?

Lets understand what are adaptable classes and what are adapter classes.

So when we adapt any resources or any nodes then that resources or nodes classes are know as adaptable class while adapter is a class which actually adapts from the adaptable class and further convert to the normal class or variables. See below picture for better understand

ii) defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL

This makes your model more accurate and working, if you did not include in your model then as we know that by default ValueMapValue String is required and when we import any component in page and if data is not found then it will show error. So to prevent from the error, we need to add DefaultInjectionStrategy.OPTIONAL and if we require that variable should have value, then we can add required annotation to particular variables.

iii) @ValueMapValue

This simply used to map our resource to their respective java variable, as we add String myname in below ValueMapValue annotation. In this step sling search myname key from the resource JCR properties and map their value to respective java variable.

iv) why we created method getMydetails() ?

So the method getMydetails() return string, which is myname variable. Actually we can’t directly access myname variable from the HTL(sightly) because myname is a private variable and it can’t access from the out side the class. This is the reason we need to create method.

But wait, Is AEM given us any rules to write method name ?

Answer is, Yes.

the method should start with get and add the method name, first letter with Capital. Like for example, if you want to add a method with mydetails name then you have to create like this: getMydetails.

Rest of the code is only Java and I hope, you have some basic knowledge of Java Language.

HTL | Sightly | HTL In AEM

What is HTL or Sightly?

Sightly is a Hypertext Template Language (HTL) specifically designed for AEM. It was introduced with AEM version 6.0. Now-a-days, slightly has been gaining importance because of its various advantages for developing websites in AEM.

So, the HTML Template Language (HTL) supported by Adobe Experience Manager (AEM) is the preferred and recommended server-side template system for HTML in AEM. It takes the place of JSP (Java Server Pages) as used in previous versions of AEM.

Sample Code of HTL

<sly data-sly-test="${properties.jcr:title && properties.jcr:description}">
    <h1>${properties.jcr:title}</h1>
    <p>${properties.jcr:description}</p>
</sly>
   

Some attributes, Syntax and their uses:

1) data-sly-use

=> The dataslyuse attribute is used to initialize the use-class within your HTL code.

=> data-sly-use.model=”com.adobe.aem.guides.wknd.core.models.DemoSlingHtl”

=> here .model is reference for the page and it act as an object and instance for the Sling model

=> above .model has taken reference for DemoSlingHtl sing model class and this can access all the properties

2) data-sly-test

=> Validates and conditionally removes the host element and it’s content. Returned ‘False’ removes the element; Returned value ‘true’ retains the element.

=> <h1 data-sly-test=”${display}”>text</h1>
Here h1 element and its content will only be rendered if ‘display’ is true.

=> <h1 data-sly-test.myVar=”${x || y || z}”>is true</h1>

=> <h1 data-sly-test=”${!myVar}”>Else This</h1>

3) Logical Operators

=> Logical Operators are used with Boolean values, where the operator returns the value of one of the specified operands. While using with non-Boolean values, they may return a non-Boolean value. They are of 3 types.

  • AND : <P data-sly-test=”${properties.jcr:title && properties.jcr:description}”>DISPLAY</p>
  • OR : <P data-sly-test=”${properties.jcr:title || properties.jcr:description}”>DISPLAY</P>
  • NOT : <p data-sly-test=”${!currentPage.hasChild}”>DISPLAY</p>

4) data-sly-list

=> List tag repeats the content of the host element for each enumerable property in the provided object.

<h6 data-sly-list=”${currentPage.listChildren}”>
    <dt>index: ${itemList.index}</dt>
    <dd>value: ${item.title}</dd>
</h6>
Where ‘item’ is the current item in the iteration & itemList is the object holding the properties.

To View all important list HTL Attributes and Syntaxes click here

Why we use HTL (Sightly) in AEM ?

The languages like of JSP (Java Server Pages) and ESP (ECMA Script Server Pages) serve well for website development in AEM, But sightly is emerging to be a preferred templating language for HTML because HTML developers can participate better in AEM project without any JAVA knowledge.

In addition, this language seems pleasing to the eye of any web developer. It is made easily understandable with its simple syntax, and efficient maintainability. Therefore, it is called “Sightly”.

Sightly, is also referred as server side template language, it enables development teams to distinctly separate logic and markup. This flexibility allows faster and easier CMS customization. It helps businesses to pursue not only broader but also comprehensive business strategy and faster time to market.

One more benefit :

Sightly is easy to adapt because it allows the front-end developers to directly work with templates in Abode Experience Manager and not have the visual clutter of JSTL or the power (and responsibility) of JSP. Thus, it becomes much easier to use it, in all the projects for web development on AEM.

How to use HTL in HTML pages in AEM?

1) Create .html file under your component or under static folder/file

2) Use sly API syntax to grab the data and show in the HTML

Let’s create Sightly in HTML page,

here, I am going to create HTL for above sling model, and they have only one data that is mydata, our code will be,

<div data-sly-use.model="com.adobe.aem.guides.wknd.core.models.DemoSlingHtl">
    

    <p>${model.mydetails}</p>

</div>
   

In the above code, first line have <div data-sly-use.model=”com.adobe.aem.guides.wknd.core.models.DemoSlingHtl”> and this tells us that this a data-sly which is used this model (com.adobe.aem.guides.wknd.core.models.DemoSlingHtl).

So in first line, we defined a reference object and it can access the all public method of DemoSlingHtl model class, and here our object name is model.

now we can write our Sightly syntax to get value of any method from model object

${model.mydetails} , here when we used mydetails with our reference variable(object/instance) then what actually called in the back end is model.getMydetails().

Here, AEM just add get in the method name and make first letter of your method name in Upper case and then call and find the actuall method. That is the reason we only written mydetails instead of getMydetails.

Thats it, now your Sling and Sightly is ready and you can add multiple data also through aem component. How to create component in AEM ?

Optimized Way to Create Sling Models and HTL

you can refer this article : create dynamic component with best approach

People also ask:

Leave a Comment