Search code examples
javaslingsightly

How do I use a sling service in sightly page without using javascript?


I have to use a sling service that I created e.g.

@Component
@Service
public class SearchServiceImpl implements SearchService {
    public SearchResults search() {
     SearchResults results = new SearchResults();
     .....
     return results;
    }
}

Now I want to call this service in my sightly without using javascript as there are chances some users wont use javascript while accessing my service. How do I call this service?


Solution

  • You could go for the use API. This requires to provide a search component class that implements the WCMUse interface.

    ...
    import com.adobe.cq.sightly.WCMUse;
    
    public class Search extends WCMUse {
    
       @Reference
       private SearchService searchService
    
       public SearchResults listResults(){ 
       ...
    

    The search component uses your service to get the actual results and provides the datamodel to the sightly template.

    <div data-sly-use.search="Search">
        <ul data-sly-list.result="${search.listResults}">
          <li>${result.title}</li>
        </ul>
    </div>
    

    The official documentation is quite helpful to achieve our goal. https://docs.adobe.com/docs/en/aem/6-1/develop/sightly/use-api-in-java.html for details