One way of doing this would be to add a test:
<div data-sly-test="${properties.altText}">
<img src="${properties.imgMobile}" alt="${properties.altText}" />
</div>
The above condition will work when altText is non-null. For cases where altText is null,
<div data-sly-test="${!properties.altText}">
<img src="${properties.imgMobile}" alt="" />
</div>
Note that alt=""
is not using Sightly syntax, so it will be ignored by the Sightly processor and will come out as alt=""
as Sightly ignores empty string literals.
As per the Sightly Documentation:
Note that an attribute (either literal or set via data-sly-attribute) whose value evaluates to the empty string will be removed in the final markup. The one exception to this rule is that a literal attribute set to a literal empty string will be preserved.
Personally, I don't think this is the most elegant solution but due to current Sightly engine's limitations for stripping empty values, this seems the most effective one.
Another option is to use empty arrays:
<!--/* Like empty strings, empty arrays remove the attribute: */-->
<div title="${[]}"></div>
<!--/* outputs: */-->
<div></div>
<!--/* But an array containing just an empty string doesn't get removed: */-->
<div title="${['']}"></div>
<!--/* outputs: */-->
<div title=""></div>
Hope this helps.