This repository has been archived by the owner on Jul 16, 2023. It is now read-only.
/
TemplateDescriptor.cs
54 lines (43 loc) · 1.55 KB
/
TemplateDescriptor.cs
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
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using MiniRazor.Utils.Extensions;
namespace MiniRazor;
/// <summary>
/// Represents a compiled Razor template.
/// </summary>
public class TemplateDescriptor
{
private readonly Type _templateType;
/// <summary>
/// Initializes an instance of <see cref="TemplateDescriptor" />.
/// </summary>
public TemplateDescriptor(Type templateType) => _templateType = templateType;
private ITemplate CreateTemplateInstance() => (ITemplate) (
Activator.CreateInstance(_templateType) ??
throw new InvalidOperationException($"Could not instantiate compiled template of type '{_templateType}'.")
);
/// <summary>
/// Renders the template using the specified writer.
/// </summary>
public async Task RenderAsync(TextWriter output, object? model, CancellationToken cancellationToken = default)
{
var template = CreateTemplateInstance();
template.Output = output;
template.Model = model?.GetType().IsAnonymousType() == true
? model.ToExpando()
: model;
template.CancellationToken = cancellationToken;
await template.ExecuteAsync();
}
/// <summary>
/// Renders the template to a string.
/// </summary>
public async Task<string> RenderAsync(object? model, CancellationToken cancellationToken = default)
{
using var output = new StringWriter();
await RenderAsync(output, model, cancellationToken);
return output.ToString();
}
}