forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplateCodePage.cs
More file actions
101 lines (85 loc) · 3.38 KB
/
Copy pathTemplateCodePage.cs
File metadata and controls
101 lines (85 loc) · 3.38 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace ServiceStack.Templates
{
public abstract class TemplateCodePage : IDisposable
{
public string VirtualPath { get; set; }
public string Layout { get; set; }
public TemplatePage LayoutPage { get; set; }
public PageFormat Format { get; set; }
public Dictionary<string, object> Args { get; } = new Dictionary<string, object>();
public TemplateContext Context { get; set; }
public ITemplatePages Pages { get; set; }
public TemplateScopeContext Scope { get; set; }
private MethodInfo renderMethod;
private MethodInvoker renderInvoker;
protected TemplateCodePage(string layout = null)
{
Layout = layout;
}
public async Task WriteAsync(TemplateScopeContext scope)
{
var renderParams = renderMethod.GetParameters();
var args = new object[renderParams.Length];
for (var i = 0; i < renderParams.Length; i++)
{
var renderParam = renderParams[i];
var arg = scope.GetValue(renderParam.Name);
args[i] = arg;
}
try
{
var result = renderInvoker(this, args);
if (result != null)
{
var str = result.ToString();
await scope.OutputStream.WriteAsync(str);
}
}
catch (Exception ex)
{
throw new TargetInvocationException($"Failed to invoke render method on {GetType().Name}", ex);
}
}
public bool HasInit { get; private set; }
public virtual TemplateCodePage Init()
{
if (!HasInit)
{
HasInit = true;
var type = GetType();
if (Format == null)
Format = Context.PageFormats.First();
var pageAttr = type.FirstAttribute<PageAttribute>();
VirtualPath = pageAttr.VirtualPath;
if (Layout == null)
Layout = pageAttr?.Layout;
LayoutPage = Pages.ResolveLayoutPage(this, Layout);
var pageArgs = type.AllAttributes<PageArgAttribute>();
foreach (var pageArg in pageArgs)
{
Args[pageArg.Name] = pageArg.Value;
}
if (!Context.CodePageInvokers.TryGetValue(type, out Tuple<MethodInfo, MethodInvoker> tuple))
{
var method = type.GetInstanceMethods().FirstOrDefault(x => x.Name.EndsWithIgnoreCase("render"));
if (method == null)
throw new NotSupportedException($"Template Code Page '{GetType().Name}' does not have a 'render' method");
var invoker = TypeExtensions.GetInvokerToCache(method);
Context.CodePageInvokers[type] = tuple = Tuple.Create(method, invoker);
}
renderMethod = tuple.Item1;
renderInvoker = tuple.Item2;
}
return this;
}
public virtual void Dispose()
{
}
}
}