DataModelUtils.cs 1.1 KB

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