Skip to main content

Sitecore Scriban Templates – Custom Functions to the Recue

 So you jumped in head first into Scriban Templates with Sitecore.  And now you hit a wall because it doesn't do that one thing you could easily have completed in MVC forms with a controller.  Well, this is where you can build your own custom functions to work within Scriban templates.  Sitecore already provides a few of these at https://doc.sitecore.com/developers/sxa/93/sitecore-experience-accelerator/en/the-embedded-functions-for-the-scriban-template.html.

So How Do You Build Your Own?

Well let's begin by discussing what we want to build.  In our project we have a need to get the nearest parent of a certain template type.  This way we can determine if the page you are viewing is part of a conference section or not.  

So first, let's build the C# code that will execute when we call the function.  We decided to add a new member to the i_item to determine if we were in a conference context and allow us to call other properties as we would need.

public class GetConferenceContext : GetScribanItemMember
    {
        protected override string MemberName => "conference";

        protected override void Resolve(GetScribanItemMembersPipelineArgs args)
        {
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            if (args.Mode.Equals(MemberMode.Name))
            {
                args.Members.Add(MemberName);
                return;
            }

            Item conference = null;
            try
            {
                if (args.Item != null)
                {
                    conference = args.Item.Axes.SelectSingleItem("ancestor-or-self::*[@@templateid='{YOUR TEMPLATE KEY HERE}']");
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error determining conference context.", ex, this);
                throw;
            }

            args.MemberValue = conference;
        }
    }

You will notice that you just need to inherit from the class GetScribanItemMember, then set the MemberName and finally override the Resolve function.  So far pretty easy.

Second, now we need to tell Sitecore that this new Scriban function is available.  We added a new configuration file in App_Config -> Include -> z.Project.Foundation.  This file adds pipelines into Sitecore to define the Scriban functions.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/">
  <sitecore>
    <pipelines>
      <getScribanItemMembers>
        <processor type="Project.Foundation.Pipelines.Scriban.ItemProcessors.GetConferenceContext, Project.Foundation" resolve="true" />
      </getScribanItemMembers>
      <generateScribanContext>
        <processor type="Project.Foundation.Pipelines.Scriban.ContextProcessors.GetSocialLink, Project.Foundation" resolve="true" />
      </generateScribanContext>
    </pipelines>
  </sitecore>
</configuration>

Here we added the ItemMember to the code above, but I also wanted to show the configuration for Context if you need to create those processors as well.  

Now, you have the code deployed, Sitecore is aware of this new function through configuration and you can use your new member extender.  Remember, in the scenario we built we extended the i_item context to now have a conference member.  Let's see a few interactions with this new member.

{{ this.conferenceEvent = sc_follow i_item.conference "Conference Event" }}

This call uses the sc_follow function from Sitecore to crawl our Conference method and return the Conference Event property on that item.  The sc_follow is a Sitecore function that 

Returns the item that is selected from a field and stores links to items. If the field can contain links to multiple items, the first item in the list is returned. If the field is empty, the function returns a null value.

This way if we are in the context of a conference it will return the property we are looking for, if not it returns a null value.   Or we can just check the id property of the conference to see if it has context. 

{{ if (i_item.conference.id | string.size > 0) }}

And then we can finally just loop through the conference children to get what we need.  This gets the nearest parent of a conference and loops through the child items.

{{  for i_childevent in i_item.conference.children }}

So as you can see, Scriban templates are very powerful in their basic form, but add this ability to extend them as you need for your project and there is no stopping them.  Good luck.

Until next time.

Comments

Popular posts from this blog

Quick Tip - Scriban Date Formatting in Sitecore

 With the Scriban syntax being new to the Sitecore platform with v9.3 there is definitely a learning curve but well worth the time investment.  So we will post short tips on things that we struggled with.  This is to share but also I will have a place to find it again when I need it. So you've created a date field in your Sitecore template and now need to format it for display purposes.  Or even better, you have styling differences depending on if the dates and years match for start and end points.  Let's show this below. First, get the date(s) in your Scriban template from the item.  In this scenario I was looping through child objects called i_child.  Using the Scriban date.parse function I can get the date value from the Sitecore field by this:     {{         this.startDate = sc_field i_child 'Event Start' | date.parse;         this.endDate = sc_field i_child 'Event End' | date.parse;     }} Now that we have the date values you can do things to check against

Sitecore 9.3 – Scriban Templates – Yes Please!

 This feature sold us on our migration to Sitecore v9.3 and using SXA.  Why was it so important in our decision?  Based purely on speed to implement.  Let's explain, but first what is Scriban? What is a Scriban Template in Sitecore? 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. And Sitecore SXA has has adopted this new templating system whole-heartedly.  It allows a lot of your custom HTML and MVC controls to brought into the content tree.  Why is this important?  Because now you don't have to create a custom controller and CSHTML to create a rendering.  You can create and use a Scriban template. For more information refer to the documentation found at  https://doc.sitecore.com/developers/sxa/93/sitecore-experience-accelerator/en/scriban-templates.html .  You can also find more documentation on the Scriban template itself at  htt