SXA Scriban extension to get link field target URL

Scriban is the new templating language which was introduced in Sitecore 9.3, it replaces the obsolete NVelocity templates in the earlier versions. If you are upgrading from earlier versions of Sitecore and used a lot of NVelocity templates, you need to convert all your NVelocity templates to Scriban as NVelocity is no longer supported in Sitecore 9.3.

Scriban is a powerful language with support to import your own .Net functions. Sitecore provides a rich set of Scriban extensions to use which meets most of the common requirements. You can find more about the out of the box Sitecore Scriban extensions here.

While using Scriban to create custom markup which can't be achieved through other Rendering Variant fields I came across a requirement to wrap a section of HTML with an anchor tag targeting to an URL set in a link field in the template. In SXA we would set the link target field on the Rendering Variant and set the Is Link property value of the Rendering Variant field to Wrapped to achieve this. However, to achieve the same using Scriban we need to access the target URL of the link field and use it as href value of the wrapping anchor tag. While there are many out of the box Sitecore Scriban extensions available, none of them gives you access to the target URL of a link type field. SO I decided to write my first custom Sitecore extension for Scriban.

Extending Scriban in Sitecore is simple and straight forward. Here are the simple steps to create a Scriban extension called sc_linktargeturl to get the target URL of a link type field...

Step 1

Create a class that implements IGenerateScribanContextProcessor interface. Inject the IContext in the constructor and store the context object to a local read-only property.

Step 2

Create a method that take item and linkFieldName as parameters and return the target URL as string.

Step 3

We need a delegate to register our custom extension with the GenerateScribanContext pipeline. Declare a local property of type delegate that matched the method signature that we just created.

Step 4

Now we need to create Process method to register our custom extension name against the instance of delegate we just created.

The final class file should look like below.

Step 5

Now create a config patch file to attach our custom processor to generateScribanContext pipeline.

Now you should be able to call your custom Scriban extension from Scriban code using {{sc_linktargeturl  i_item "LinkFieldName"}}.

You can also create your own item extensions by creating custom pipeline processor for getScribanItemMembers pipeline. More on this in a future post.

Hope this helps!


Popular posts from this blog

Using Sitecore FXM to update and track contacts

Sitecore Content Search API - Random Search Results using Solr