How do I include a resource in a Sightly template only if it exists?
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
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>