Wednesday, February 7, 2018

Access Reference Fields in SXA Rendering Variant

In this article I demonstrate how to create an NVelocity tool to access properties from a Sitecore ReferenceField.

As a followup to my post on building a custom tool in SXA, I wanted to share a new discovery which makes greater use of NVelocity.

If you have used Rendering Variants in SXA you may have come across the token $item. With this token you are able to access data on the page item. Rather than have the page contain all of the data, why not make use of a ReferenceField such as a droptree and get the data from that item.

Update 20180914: I started thinking about blogging a new article to discuss the use of Google Static Maps, but then remembered that this article shows the use of that! Once consideration to make is that the images could be lazy-loaded using some simple JavaScript if you wish to reduce hits against your API quota. In the Summer of 2018 Google started charging, so reducing this could help your company save some big bucks!

Location Page with Reference to POI

SXA provides a way to store Points of Interest (POI) and link to a page. In the following example, you can see that the My Location POI allows for a link to a page. I personally don't like relying on this direction of reference because I expect the page to either inherit from POI or reference a POI.


In my solution, I create a new field on the page called "POI" and link back to the POI. As you see below, the new field points back to the global data directory so the user can pick from an existing list of POIs.


I would imagine an automated process mapping the POI to a page, but that's a problem to solve for another day.


Build the Tool

Getting back to the item tool, we need to create a new method for accessing a reference field.

Create a tool called $itemFieldTool and then use it in the rendering variant.

Use the Tool

In my use case, I needed to show a Google Static map on the page. Here is the rendering variant I setup.


The Map VariantTemplate contains the data from the gist. In the below example we have a Google Static Map getting loaded; you may want to lazy-load to reduce hits against your quota. Consider creating another tool ($mapTool) to return the MapsProvider key from SXA.



The part that I found really cool was that you can create a new variable called $refItem and it would appear in the same context as $item.

This is where the fun part is in the gist:

#set($refItem = $itemFieldTool.GetItemReferenceItem($item, "POI"))

I hope this helps you build something super awesome. If you use it please share a link in the comments so others can celebrate your success.

- Michael