Get a data-sly-list element as a jsonarray

Avatar

Avatar

rampai

Avatar

rampai

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)

Avatar

Avatar

Ankur_Khare

MVP

Avatar

Ankur_Khare

MVP

Ankur_Khare
MVP

10-10-2019

In your java class you can convert the data to json using GSON and send back to frontend -

Gson().toJson("data");

Answers (4)

Answers (4)

Avatar

Avatar

rampai

Avatar

rampai

rampai

13-10-2019

Thanks. This is precisely what I did in the end.

Avatar

Avatar

Ankur_Khare

MVP

Avatar

Ankur_Khare

MVP

Ankur_Khare
MVP

23-10-2019

Could you pls mark it as correct so that it will help others as well..

Avatar

Avatar

Arun_Patidar

MVP

Total Posts

3.0K

Likes

1.1K

Correct Reply

840

Avatar

Arun_Patidar

MVP

Total Posts

3.0K

Likes

1.1K

Correct Reply

840
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. 

    } 

Avatar

Avatar

ArpitVarshney

MVP

Avatar

ArpitVarshney

MVP

ArpitVarshney
MVP

10-10-2019

Hi,

Please refer below to pass data from sightly to sling model:

https://sling.apache.org/documentation/bundles/scripting/scripting-htl.html#passing-parameters

After passing the data to sling model you can write your custom code in Sling model to convert it to json.

Regards,

Arpit Varshney