Search code examples
aemsightlyhtl

HTL Access Property Without Getter


I'm writing an AEM component and I have an object being returned that is a type from an SDK. This type has public properties and no getters. For simplicity, it might be defined like this:

class MyItem {
    public String prop1;
    public String prop2;
}

Now normally, I would need a getter, like so:

class MyItem {
    public String prop1;
    public String prop2;

    public String getProp1() {
        return prop1;
    }
}

But I do not have this luxury. Right now, I've got a Java implementation that uses another type to resolve this, but I think it's sort of crazy that HTL doesn't allow me to just access prop1 directly (it calls the getter). I've reviewed the documentation and can't see any indication of how this could be done. I'd like to be able to write:

${item.prop1}

And have it access the public property instead of calling getProp1().

Is this possible?


Solution

  • From the official documentation

    Once the use-class has initialized, the HTL file is run. During this stage HTL will typically pull in the state of various member variables of the use-class and render them for presentation.

    To provide access to these values from within the HTL file you must define custom getter methods in the use-class according to the following naming convention:

    A method of the form getXyz will expose within the HTL file an object property called xyz. For example, in the following example, the methods getTitle and getDescription result in the object properties title and description becoming accessible within the context of the HTL file:

    The HTL parser does enumerate all the public properties just like any java enumeration of public fuields which include getters and public memebers.

    Although it is questionable on whether you should have public variable but thats not part of this discussion. In essence ot should work as pointed by others.