Friday, April 21, 2017

Custom Rendering Variant Token Tool for SXA

Sitecore Experience Accelerator (SXA) provides a great way to alter how components render using a feature called Rendering Variant. The following post describes how I developed a new Rendering Variant tool that implements NVelocity templates. I found a way to extend a feature built into the great SXA.

For those that have not yet worked with NVelocity, it's essentially a mechanism for converting tokens into other text. This is often used in Sitecore standard values where you use $name to populate the title field.

UPDATE: SXA comes with some tools that you can take advantage of right now called $dateTool and $numberTool. Read more about them here and here.

Problem Statement

Marketing would like to have the page Url output in the website global search results.


As you can see above, the rendering shows a title, description, and url. Unfortunately  I was not able to figure out how to do this OOTB with SXA. Fortunately it took very little effort to write code for this.

Setup

There are a few steps you need to take in order for this to work.
  1. Have a need for it. Duh.
  2. Setup a Visual Studio project, something like Company.Foundation.Variants.
  3. Reference the SXA library Sitecore.XA.Foundation.Variants.Abstractions.dll, Sitecore.Kernel.dll, and Sitecore.NVelocity.dll.
  4. Add a new class to define the tool, such as Company.Foundation.Variants.NVelocityExtensions.LinkTool.
  5. Add a new class to register the tool, such as Company.Foundation.Variants.Pipelines.GetVelocityTemplateRenderers.AddTemplateRenderers.
  6. Patch the new pipeline in to getVelocityTemplateRenderers.
Here's a little snippet to get you started.

Usage

In the Rendering Variant configured for search results, add a VariantTemplate item. The template field should then contain something like the following:

<a href="$linkTool.GetItemLink($item)">$linkTool.GetItemLink($item,true)</a>

Here is the html set within the VariantTemplate.


That's pretty much all there is to setting it up. Hope you find this feature as helpful as I did!

No comments:

Post a Comment