Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include a resource in a Sightly template only if it exists?

Tags:

sling

sightly

I would like to use data-sly-resource to include a resource, but only if it exists, e.g.

<div class="pull-right" data-sly-resource="/content/blog/stats"></div>

If the resource does not exist the script execution fails with the following error message: Cannot find servlet to handle resource /content/blog/stats . From the Request Progress listing I can see that it's a SyntheticResource:

TIMER_START{resolveServlet(SyntheticResource, type=null, path=/content/blog/stats)}

How can I include the resource conditionally, only if it exists?

like image 659
Robert Munteanu Avatar asked Nov 02 '15 20:11

Robert Munteanu


People also ask

What is the use of unwrap element and attribute in sightly?

data-sly-unwrapRemoves the host element from the generated markup while retaining its content.

How does sightly differ from other templating systems?

On the other hand, sightly shows its significance in enabling Java developers to focus on the backend code independently. This specific feature distinguishes sightly from other templating systems where Java developers should have little front-end knowledge of integration.

What is sly in AEM?

data-sly-element attribute with example in AEM: data-sly-element is a sightly/htl attributes which replaces the element name of the host element.


2 Answers

In this case the best solution would be to allow your redis/stats component to correctly handle the situation when a Resource it's supposed to render is a SyntheticResource or, more generally, doesn't provide any properties.

Therefore the calling Sightly snippet should be:

<div class="pull-right" data-sly-resource="${'/content/blog/stats' @ resourceType='redis/stats'}"></div>

This forces the rendering to be made by your redis/stats component, even if the /content/blog/stats resource doesn't exist (well, Sling will return a SyntheticResource, like you mentioned).

In your redis/stats component you could then try this safeguard:

<div class="blog-stats" data-sly-test="${properties}">
<!--/* This whole block will only be rendered if properties is not empty */-->
</div>

which would render the div.blog-stats only if the properties map was not empty [0].

[0] - https://github.com/Adobe-Marketing-Cloud/sightly-spec/blob/1.1/SPECIFICATION.md#225-test

like image 121
Radu Cotescu Avatar answered Oct 13 '22 02:10

Radu Cotescu


If the resource you need to include (e.g. stats) is a child of the current resource, then this might work:

<div data-sly-test="${resource['stats/jcr:primaryType']}"
    class="pull-right" 
    data-sly-resource="stats"></div>
like image 42
ccpizza Avatar answered Oct 13 '22 00:10

ccpizza