Experience Sitecore ! | Image tag wrapped with anchor both having own classes but without any unwanted component wrappings, easy? Not OOB in SXA, but here's the fix!

Experience Sitecore !

More than 200 articles about the best DXP by Martin Miles

Image tag wrapped with anchor both having own classes but without any unwanted component wrappings, easy? Not OOB in SXA, but here's the fix!

Note! The code used in this post can be cloned from GitHib repository: SXA.Foundation.Variants

Image Link rendering variant field

This is quite powerful and at the same time very simple rendering variant field - it nicely renders <img> tag surrounded with <a> anchor tag without any of other unwanted wrappings normally coming when nesting components in SXA, as below:

<a href="http://link.to/internal-or-external-item" class="individual-class-for-anchor">
    <img src="/-/Media-item-from-sitecore" class="individual-class-for-image"/>
</a>
What is specific - is that you can attach individual classes to each element's node!

A good advantage is that an image from media library can be statically referenced or taken out of a context item field of Image type. Please note, that statistic reference always takes over a context field, if both set.

Another not easy achievable OOB feature - is the ability to specify individual CSS classes for both <a> and <img> tags. If link is not set - it will simply render an image with class



The image above shows a usage example where I use this variant field to show a company logo in header, so that it is a link to a home page and both elements have their front-end CSS styles set.
In give example a static reference to media item (image with company logo) is used, since that is a header implementation, which means components sit on a partial design and it becomes a context item. Image is being referenced only once on a header, so there is no need to create new instances exposing a datasource with the only purpose of referencing an image - with this approach we can  reference media items directly!

As usual, the entire code and the Sitecore package with fields templates are located in GitHub repository for SXA.Foundation.Variants, you can also find a documentation on usage there 

Pingbacks and trackbacks (1)+

Comments are closed