Friday, 1 September 2017

Design Sitecore SXA components using Variant Template

In my previous blog post we talked about Sitecore SXA Rendering Variants and added variant fields to the variant definition.
The above variant did give us an option to include multiple fields but there can be a case where we have to extend the component by changing the HTML as well.
Below are the steps which will enable us to add a custom HTML to any Sitecore SXA component: (Continuing with the page list example from last blog post)

  • If we add a new Field Variant for our image, we get the below HTML:

But many a times the “Agency” (Front end devs) want the image to be lazy loaded and follow a set HTML pattern.

  • To have our custom HTML design for image field, first need to right click on Variant definition and add a new Variant “Template” and name it as the Image field name: (in my case it’s called Image)

  • This gives us a Multiline text field called as “Template” under Variant Details.
  • This field can be used to inject your HTML of Image

         Above is how we define our custom HTML to render the image field for us.

      Now to make it work dynamically and read the image & anchor href from the field we need tokenize the fields and read them through code.

  • We need to inject our code in the “getVelocityTemplateRenderers” pipeline after “InitializeVelocityContext” process and extend “AddTemplateRenderers” class.

  • Add the FieldTokens class with the helper methods:


-          And finally add the patch to insert the logic after “GetVelocityTemplateRenderers”.

      Once we have added the code we can verify that the patch is applied correctly in showconfig:
      Now, we just need to add the tokens in the sitecore Nvelocity template item:
    And that’s it. It will give the image field a new HTML:
   I hope this approach can save a lot of time and effort to create a custom component and just extend the existing one with variants.

No comments:

Post a Comment