All Articles

SXA - Functions with Scriban


Scriban is a fast, powerful, safe, and lightweight scripting language and engine for .NET, which was primarily developed for text templating with a compatibility mode for parsing liquid templates.

-Scriban Github page

Scriban with SXA

When building rendering variants with SXA, Scriban templates are particularly useful. The field renderers, sections, and tags can be used to build rendering variants. However, when we need to add some complex logic to the variants, Scriban templates are used. Refer to the official documentation for Scriban templates with SXA here.

Functions with Scriban

Scriban has several built-in functions you can use while building your components with Scriban templates.

Here is the link to the page to the Scriban built-ins.

Building your own functions with Scriban

There are a few limitations when building functions with Scriban for SXA.

  • The functions we build in a template can only be used within that template. To reuse the function in a different template, we will have to copy over the function.
  • Although Scriban has different kinds of functions to offer, I could get only Simple Functions to work. Anonymous functions did not look much useful for SXA, so I did not try it. Parametric functions did not work. This may be due to the fact that it only works on a higher version of Scriban.
  • I could not get multiple return statements to work.

Please let me know in the comments if you got any workaround around the above limitations.

Below is an example of a function I built to use a GUID as a string as a CSS class:

{{func stringifyGuid
   ret ($0 | string.downcase | string.remove "{" | string.remove "}")


guidString = stringifyGuid

Below is another function I built to use a default link when a media link is null/empty or ”#“:

{{func returnIfEmptyLink
  $value = $0
  if($0 == null || $0 == "" || $0 == "#")
    $value = $1
  ret ($value)


defaultImage = sc_follow i_card 'Default Image' | sc_medialink
myImageSrc = (sc_follow i_card 'My Image' | sc_medialink) | returnIfEmptyLink defaultImage

Note in the above example that, I could not get multiple return statements to work. That is why I used a variable to assign the return value instead.

Feedback and Suggestions are welcome!

Happy Sitecoring!!

Published Jul 4, 2022

Sitecore MVP Technology 2024-23. Web Developer with rich experience in Sitecore and ASP.NET MVC.