Sightly + Sling Models Amazing Combination

I’m very impressed with Sling Models, they provide easy and very effective binding mechanism. The combination of Sightly and Sling Models is simply superb. It has made the developers life very easy. Here is a simple example of retrieving the multifield values using Sling Models and Sightly.

The screen shot below shows the node structure of the multifield. The multifield has 2 field, a textfield and a pathfield. “item” nodes store the value of each row of the multifield. “headermenu” is the component node and “menuitems” is the multifield node which holds the item node.

Multifield

 

 

 

 

Now the logic to retrieve the multifield values. First the Model class.

Model Class:

modelclass

 

 

 

 

 

 

 

 

 

 

 

Sightly Code

sightly

 

 

 

 

When you use “data-sly-use” and assign it to Model class, it will pass the current resource object if I adapt my Model class to Resource. I can inject properties and the nodes under the current resource just by Injecting the variable. Please make sure that the property names  and the node names should match exactly with the variables of the Model.

In the above model class, I’m just injecting menuitems node and in the sightly class just retrieving the nodes under it via listChildren method. I did not use even a single get statement in my code.

More information about Sling Models: https://sling.apache.org/documentation/bundles/models.html

Don’t forget to add your package which contains the Model class to your Bundle pom. Refer screen shot below:

pom

 

7 responses to “Sightly + Sling Models Amazing Combination”

  1. Ankur Mittal Avatar

    Check this out as well. My colleague delivered a session on Sling Models.
    http://accunitysoft.com/sling-models-in-aem/

    1. rmengji Avatar

      Nice information!

  2. Ankur Avatar

    Rahul: Check the new series on SLing Models. You might find it useful.
    http://www.accunitysoft.com/sling-model-sightly-part/
    There are 4 parts to it

  3. Dhiraj Agarwal Avatar
    Dhiraj Agarwal

    Thanks for the information Rahul!

    At first this didn’t work due to javax.inject.Inject getting imported from org.apache.sling.scripting.java instead of org.apache.sling.models.api. This was resolved by adding org.apache.sling.models.api in the maven-bundle-plugin configuration.

    Source : http://stackoverflow.com/questions/25324415/cannot-get-set-data-from-sling-models

  4. mallik Avatar
    mallik

    I think i did all that is mentioned in the blog, not sure what is missing. i couldnt render the menulabel and menulink.

  5. […] a Sling model, like explained beautifully in this very good blog entry, it is easy to render the values from all of the nodes […]

Leave a comment