In simple terms, Sling Model is a java class that facilitates injection of data from JCR into a Java variable.
Let's take an example of a Simple Text Field "Title".
We can access its value directly like this ${properties.title}.
However, What if we need to write some custom business logic based on this value? To do so we utilize Sling Model.
Now, lets write a Sling Model for this field.
import javax.annotation.PostConstruct;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MyFirstSlingModel {
@ValueMapValue
String title;
@PostConstruct
protected void init() {
title = title.concat(" Updated By Sling Model");
}
public String getTitle() {
return title;
}
}
Here, annotation @ValueMapValue plays major role. It injects value stored in JCR and maps it to java variable title. We then are doing a simple operation of concatenating " Updated By Sling Model" to the authored value of title.
Let's access this updated value in html:
<section
data-sly-use.slingmodelobj="com.aemblog.core.models.MyFirstSlingModel">
<h3>Title From Properties: ${properties.title}</h3>
<h3>Title From Sling Model: ${slingmodelobj.title}</h3>
</section>
Here, the data-sly-use attribute declares that we want to use the class "com.aemblog.core.models.MyFirstSlingModel" and "slingmodelobj" is the local identifier(after the dot in data-sly-use.slingmodelobj) that is used within the HTL file to identify the class. The scope of this identifier is global within the file, after it has been declared. It is not limited to the element that contains the data-sly-use statement.
We will write ${slingmodelobj.title} to access updated value where slingmodelobj is the local identifier of the Sling Model and title is the java variable name inside it.
This is how the values will come up:
In the above example just the @ValueMapValue annotation was used. However, there are other available injectors. Find more about them here.
That's all for today! If you've found this blog post informative or helpful, I’d greatly appreciate it if you could give it a like. It keeps me motivated 💛
Enjoying my ad-free blog? Support by buying me a coffee! I've kept this space ad-free, sponsoring it myself to maintain its purity. Your contribution would help keep the site afloat and ensure quality content. Thanks for being part of this ad-free community.
Comentarios