0

我正在尝试使用 Scriban 模板引擎来支持多循环。例如

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());

我得到的输出像

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

我希望基于我们应该在子服务中循环的键,但它没有发生。任何人都可以帮助我吗?

我的第二个问题是 Scriban 模板引擎支持嵌套循环吗?提前致谢

4

1 回答 1

0

Scriban 确实支持嵌套循环。我已经更新了您的代码以显示您将如何执行此操作。我已根据您的要求更新了代码和结果。

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());

这将导致以下输出:

ServiceName: emailContent 
SubServices: 
  1. PingSubService
  2. UrlSubService
 
ServiceName: mailContent 
SubServices: 
  1. PingSubService
  2. UrlSubService
于 2020-07-14T18:59:33.580 回答