Get a data-sly-list element as a jsonarray

rampai

10-10-2019

How can we pass a list from HTL to a sling model?

I need a nested list to be converted into JsonArray format.

<div data-sly-list="${values}">

     <h1>${item.title}</h1>

     <p>${item.description}</p>

</div>

Now I want the same thing as a json string from ${values}:

[{"title":"test1", "description":"desc1"},{"title":"test2", "description":"desc2"}]

Any inputs would be helpful.

Accepted Solutions (1)

Accepted Solutions (1)

Answers (4)

Answers (4)

Arun_Patidar

MVP

11-10-2019

Create a sling model and adapt usiing SlingHttpServletRequest.class

Example:

<!-- info.html -->

<div data-sly-use.info="${'TestModel' @ text='Some text'}">

    <p>${info.reversed}</p>

</div>

Sling model

import org.apache.sling.api.SlingHttpServletRequest; 

import org.apache.sling.models.annotations.Model; 

import org.apache.sling.models.annotations.Optional; 

import org.apache.sling.models.annotations.injectorspecific.RequestAttribute; 

 

 

@Model(adaptables = SlingHttpServletRequest.class) 

public class TestModel { 

@RequestAttribute 

@Optional 

private String text; 

@PostConstruct 

    public void init() { 

        //we can read the values directly here. 

    }