DataModelUtils.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using System;
  2. using System.Collections.Generic;
  3. using InABox.Core;
  4. using Scriban;
  5. using Scriban.Runtime;
  6. namespace PRSDesktop
  7. {
  8. public static class DataModelUtils
  9. {
  10. public static string ParseTemplate(DataModel model, string data)
  11. {
  12. if (string.IsNullOrWhiteSpace(data))
  13. return "";
  14. var template = Template.Parse(data);
  15. if (template.HasErrors) throw new Exception(string.Join("\n", template.Messages));
  16. var templatecontext = new TemplateContext
  17. {
  18. MemberRenamer = member => member.Name
  19. };
  20. var so = new ScriptObject();
  21. ScriptObjectExtensions.Import(so, "string.to_base64", new Func<byte[], string>(b => Convert.ToBase64String(b)));
  22. var tables = model.AsDictionary;
  23. foreach (var key in tables.Keys)
  24. {
  25. var objects = new List<object>();
  26. foreach (var tablerow in tables[key].Rows)
  27. objects.Add(tablerow.ToObject(key));
  28. so.Add(key.Name, objects);
  29. }
  30. templatecontext.PushGlobal(so);
  31. return template.Render(templatecontext);
  32. }
  33. }
  34. }