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

kmb picture kmb · Jan 21, 2015 · Viewed 20.8k times · Source

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?

Answer

Tomek Rękawek picture Tomek Rękawek · Jan 21, 2015

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.