AEM 6.0 Mature Child Nodes

I have a question related to using Sightly to access child nodes of a component. I have a template that pulls into a basic image component using a sly-resource for example.

<div class="${wcmmode.edit ? 'image-edit image' : 'image'}" data-sly-resource="${ 'heroImage' @ resourceType='/libs/foundation/components/image', appendPath='image', selectors='fileReference' }"> </div>

      

What I would like to do is change the css class based on whether or not this image component actually has a set of images. For this, I was planning to access the image component node and read its file link. Something along the line

<h1>${ properties["heroImage"] }</h1>

      

Unfortunately, this won't work. My question is how can I access the heroImage resource file share from my template by treating it as a child node.

Thanks Harry

+3


source to share


2 answers


In AEM6, it is not possible to access child nodes and their properties directly from the Sightly template without preparing the data in the Use-API.

This is one way how you can prepare this data, so in your CQ component, you usually have something like the following two files.

<!-- template.html -->
<h1 data-sly-use.logic="Logic">
    ${logic.heroImage.fileReference}
</h1>

      

and



<!-- Logic.java -->
package apps.PATH.TO.YOUR.COMPONENT.FOLDER;

import com.adobe.cq.sightly.WCMUse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;

public class Logic extends WCMUse {
    private static final String CHILD_NODE = "heroImage";
    private ValueMap childProperties;

    @Override
    public void activate() throws Exception {
        Resource childResource = getResource().getChild(CHILD_NODE);
        childProperties = childResource.adaptTo(ValueMap.class);
    }

    public ValueMap getHeroImage() {
        return childProperties;
    }
}

      

You can also move the Logic.java file to the OSGi package, then you obviously change the package name and in the template to call this class you need to provide the full package name: <h1 data-sly-use.logic="com.PATH.TO.YOUR.PACKAGE.Logic">

Hope it helps Gabriel

+5


source


Since at least AEM 6.1 (Sling API bundle 2.7.0) there is a method getValueMap()

in the Sling Resource API, Now you can just use:

${resource.valueMap.fileReference}

      



See also this new question: How do I access the properties of a data list item in Sightly?

+3


source







All Articles