Search code examples
c#.net.net-coretemplate-enginescriban

Scriban Template Engine Multi loop Supports


I am trying to use Scriban Template Engine for multiple loop support. For Example

string bodyTextSub = "{{ for service in services }} ServiceName: {{ service }} {{ end }}" +
                "{{ for subservice in subServiceList }} SubServiceName: {{ subservice }} {{ end }}";
List<string> subServiceList = new List<string>
            {
                "PingSubService",
                "UrlSubService"
            };
            Dictionary<string, List<string>> serviceDictionary = new Dictionary<string, List<string>>()
            {
                {"emailContent", subServiceList},
                {"mailContent", subServiceList}
            };

            var template2 = Template.Parse(bodyTextSub);
            var result2 = template2.Render(new { services = serviceDictionary });
            Console.WriteLine(result2.ToString());

I am getting the output like

ServiceName: {key: emailContent, value: [PingSubService, UrlSubService]}

I want that based on the key we should loop in the subservices but it is not happening. Can anyone help me in this ?

My second question does Scriban Template Engine Supports nested looping ? Thanks in Advance


Solution

  • Scriban does support nested looping. I've updated your code to show how you would do this. I've updated the code and the results per your request.

    var bodyTextSub = @"{{ for service in services }} 
    ServiceName: {{ service.key }} {{$counter = 1}}
    SubServices: {{ for subService in service.value }}{{ `
      `; $counter + `. `; $counter = $counter + 1 ; }}{{ subService }}{{ end }}
    {{ end }}";
    var subServiceList = new List<string>
    {
        "PingSubService",
        "UrlSubService"
    };
    var serviceDictionary = new Dictionary<string, List<string>>()
    {
        {"emailContent", subServiceList},
        {"mailContent", subServiceList}
    };
    
    var template2 = Template.Parse(bodyTextSub);
    var result2 = template2.Render(new {services = serviceDictionary});
    Console.WriteLine(result2.ToString());
    

    This will result in the following output:

    ServiceName: emailContent 
    SubServices: 
      1. PingSubService
      2. UrlSubService
     
    ServiceName: mailContent 
    SubServices: 
      1. PingSubService
      2. UrlSubService