AEM6 Sightly: How to pass a parameter from HTML to a method from Java-model class?

21,673

Java Use-API doesn't support passing parameters to the getter method. You may pass parameters once, during the Use class initialization. Take a look on this example inspired by the Sightly documentation:

<!-- info.html -->
<div data-sly-use.info="${'Info' @ text='Some text'}">
    <p>${info.reversed}</p>
</div>

Java code:

// Info.java
public class Info extends WCMUse {

    private String reversed;
     
    @Override
    public void activate() throws Exception {
        String text = get("text", String.class);
        reversed = new StringBuilder(text).reverse().toString();
    }
  
    public String getReversed() {
        return reversed;
    }
}

Such kind of parameters makes sense only when the Use class is invoked from data-sly-template elements (otherwise parameters could be as well hardcoded in Use class). More info can be found in the following chapter of aferomentioned documentation.

Share:
21,673
kmb
Author by

kmb

Updated on July 05, 2022

Comments

  • kmb
    kmb almost 2 years

    I wanted to pass a parameter from html to WCMUse class.

    Java:

    public class ComponentHelper extends WCMUse {
    
        public void activate() throws Exception {}
    
        ...
    
        public String methodA(String parameter1) {
            ...
        }
    
        public String getParam() {
            String param = "";
            ...
            return param;
        }
    }
    

    HTML:

    <componentHelper data-sly-use.componentHelper="ComponentHelper" data-sly-unwrap />
    ...
    <div>
        ${componentHelper.methodA @ parameter1=componentHelper.param}
        <!--/* Also tried: ${componentHelper.methodA @ componentHelper.param} */-->
    </div>
    

    Unfortunately, it looks like I can't pass any parameter into the method. Is there any way to pass a parameter to WCMUse class from html?

  • samir
    samir over 8 years
    Hi @Tomek @kmb I am also facing a similar situation where I have to pass property of one java use handler (which I have initiated before) to the activate of another java handler. Code is like <div data-sly-unwrap data-sly-use.softwarehandler="${'com.software.wcm.sightly.ha‌​ndlers.SoftwareHandl‌​er' @ slaId=anotherhandler.slaId}"> but in this anotherHandler java class slaId I am getting as null. If I use ${anotherhandler.slaid} then its not working, if I use '${anotherhandler.slaid}' then its coming as string. What way can I achieve this ?
  • Ma Kro
    Ma Kro over 4 years
    Just an update: with Sling Models you don't have to write such activate method, and you can just inject those params with @Inject