Sitecore SXA – Using responsive images in Scriban

Yesterday a question on slack on how to use the alt text with Responsive Images in scriban triggered my quriosity. The way that the Responsive Image was used, was by using the sc_execute function, which renders a Variant Field that is located underneath the Scriban template. I was wondering if there was a way to do it within plain sriban, but unfortunately this isn’t possible out of the box.

As always, and you’ve might heard this before; Sitecore being Sitecore, we’re able to extend the functionality pretty easy. We can add a custom scriban function that does all of the magic for us.

Implementation

AddResponsiveImage.cs

using Sitecore.XA.Foundation.Scriban.Pipelines.GenerateScribanContext;
using Scriban.Runtime;
using System;
using Sitecore.Data.Items;
using Sitecore.XA.Foundation.RenderingVariants.Fields;
using Sitecore.XA.Foundation.RenderingVariants.Pipelines.RenderVariantField;
using Sitecore.XA.Foundation.Variants.Abstractions.Pipelines.RenderVariantField;
namespace Example
{
    public class AddResponsiveImage : IGenerateScribanContextProcessor
    {
        public void Process(GenerateScribanContextPipelineArgs args)
        {
            args.GlobalScriptObject.Import("cs_responsiveimage", new Func<Item, string, string, string, string, string>(RenderResponsiveImage));
        }
        private string RenderResponsiveImage(Item item, string fieldName, string defaultSize, string sizes, string widths)
        {
            var responsiveImageProcessor = new RenderResponsiveImage();
            var args = new RenderVariantFieldArgs(new VariantResponsiveImage()
            {
                DefaultSize = defaultSize,
                FieldName = fieldName,
                Sizes = sizes,
                Widths = widths
            }, item);
            responsiveImageProcessor.RenderField(args);
            return args.Result;
        }
    }
}

Feature.ScribanExtensions.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <generateScribanContext>
        <processor type="Example.AddResponsiveImage, Example" resolve="true"/>
      </generateScribanContext>
    </pipelines>
  </sitecore>
</configuration>

Usage

When the example code is deployed, you should be able to use the newly added function from within your Scriban templates.

cs_responsiveimage {item} {fieldname} {defaultSize} {sizes} {widths}
cs_responsiveimage i_item "MyImageField" "400" "(max-width: 320px) 280px, (max-width:480px) 440px, 800px" "320, 480, 800"

Leave a Reply

Your email address will not be published. Required fields are marked *