-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_render.go
91 lines (73 loc) · 1.71 KB
/
2_render.go
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
package moontpl
import (
"github.com/nvlled/htmlformat"
lua "github.com/yuin/gopher-lua"
)
func (m *Moontpl) RenderFile(filename string) (string, error) {
L := m.getState(filename)
defer m.luaPool.Put(L)
lv, err := m.renderFile(L, filename)
if err != nil {
return "", err
}
if lv.Type() == lua.LTNil {
return "", nil
}
output := L.ToStringMeta(lv).String()
if wholeExt(filename) == ".html.lua" {
output = htmlformat.Format(output)
}
return output, nil
}
func (m *Moontpl) RenderString(luaCode string) (string, error) {
L := m.getState("-")
defer m.luaPool.Put(L)
if err := L.DoString(luaCode); err != nil {
return "", err
}
lv := L.Get(-1)
if lv.Type() == lua.LTNil {
return "", nil
}
output := L.ToStringMeta(lv).String()
output = htmlformat.Format(output)
return output, nil
}
func (m *Moontpl) renderFile(L *lua.LState, filename string) (lua.LValue, error) {
if hasPathParams(filename) {
var params pathParams
params, filename = extractPathParams(filename)
pageData := PageData{}
for k, v := range params {
pageData[k] = v
}
m.SetPageData(L, pageData)
}
if err := L.DoFile(filename); err != nil {
return lua.LNil, err
}
lv := L.Get(-1)
if lv.Type() == lua.LTNil {
return lua.LNil, nil
}
if mod, ok := getLoadedModule(L, "page").(*lua.LTable); ok {
onPageRender, isFunc := mod.RawGetString("onRender").(*lua.LFunction)
if !isFunc {
onPageRender, isFunc = mod.RawGetString("onRenderDefault").(*lua.LFunction)
}
if isFunc {
err := L.CallByParam(lua.P{
Fn: onPageRender,
NRet: 1,
Protect: true,
}, lv)
if err != nil {
return lua.LNil, err
}
if ret := L.Get(-1); ret != lua.LNil {
lv = ret
}
}
}
return lv, nil
}