AEM 6.0 Sightly Child Nodes

2020-06-06 07:06发布

问题:

I have a question around using Sightly to access child nodes of a component. I have a template which pulls in a basic image component using data-sly-resource, like so.

<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 that image component actually has an image set. For this my plan was to access to the image component node and read its file reference. Something along the line of

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

Unfortunately this doesn't work. My question is how can I access the fileReference of the heroImage resource from my template, seeing as its a child node.

Thanks, Harry

回答1:

In AEM6, it isn't 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 that data, so in your CQ component, you'd typically have something like 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 into an OSGi bundle, then you'd obviously change the package name, and in the template to call that class, you'd then have to provide the fully qualified package name: <h1 data-sly-use.logic="com.PATH.TO.YOUR.PACKAGE.Logic">

Hope that helps, Gabriel



回答2:

Since at least AEM 6.1 (Sling API bundle 2.7.0) there is a getValueMap() method on the Sling Resource API. So you can now simply use:

${resource.valueMap.fileReference}

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