This repository was archived by the owner on Dec 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTemplateLoader.cs
More file actions
65 lines (59 loc) · 1.96 KB
/
TemplateLoader.cs
File metadata and controls
65 lines (59 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using Scriban;
using Scriban.Parsing;
using Scriban.Runtime;
using CommonMark;
using System.Text;
namespace WebsiteProxy
{
public static class TemplateLoader
{
public static string Render(string path, Dictionary<string, object>? parameters, Log? log = null)
{
ScriptObject script = new ScriptObject(); // Used for sending arguments to html template.
if (parameters != null)
{
foreach (KeyValuePair<string, object> parameter in parameters)
{
script.Add(parameter.Key, parameter.Value);
}
}
TemplateContext templateContext = new TemplateContext();
templateContext.TemplateLoader = new MyTemplateLoader();
templateContext.PushGlobal(script);
Template template = Template.Parse(File.ReadAllText(path, Encoding.UTF8));
string rendered = template.Render(templateContext);
if (log != null)
{
log.Add("Rendered", LogColor.Data);
}
return rendered;
}
class MyTemplateLoader : ITemplateLoader
{
public string GetPath(TemplateContext context, SourceSpan callerSpan, string templateName) // TODO: Adapt for relative paths.
{
return Path.Combine(Util.currentDirectory, templateName.TrimStart('/', '\\'));
}
public string Load(TemplateContext context, SourceSpan callerSpan, string templatePath)
{
if (!Util.IsInCurrentDirectory(templatePath))
{
throw new ArgumentException("The file \"" + templatePath + "\" is not in the working directory.");
}
if (!File.Exists(templatePath))
{
throw new ArgumentException("The file \"" + templatePath + "\" does not exist.");
}
if (new string[] { ".txt", ".md" }.Contains(new FileInfo(templatePath).Extension.ToLower()))
{
return CommonMarkConverter.Convert(File.ReadAllText(templatePath, Encoding.UTF8));
}
return File.ReadAllText(templatePath, Encoding.UTF8);
}
public ValueTask<string> LoadAsync(TemplateContext context, SourceSpan callerSpan, string templatePath)
{
throw new NotImplementedException();
}
}
}
}