Skip to main content
rampai
Community Advisor
Community Advisor
10月 11, 2019 6:31 上午 UTC
已解決

Get a data-sly-list element as a jsonarray

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.

此主題已關閉回覆。
Ankur_Khare
Community Advisor
10月 11, 2019 6:54 上午 UTC

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

Gson().toJson("data");

Ankur

5 則回覆

ArpitVarshney
Community Advisor
Community Advisor
10月 11, 2019 6:49 上午 UTC

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

翻譯
Ankur_Khare
Community Advisor
Community Advisor
10月 11, 2019 6:54 上午 UTC

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

Gson().toJson("data");

翻譯
Ankur
arunpatidar
Community Advisor
Community Advisor
10月 11, 2019 6:56 下午 UTC

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. 

    } 

} 

翻譯
Arun Patidar
rampai
Community Advisor
rampaiCommunity Advisor作者
Community Advisor
10月 13, 2019 2:32 下午 UTC

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

翻譯
Ankur_Khare
Community Advisor
Community Advisor
10月 23, 2019 11:20 上午 UTC

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

翻譯
Ankur