-
Notifications
You must be signed in to change notification settings - Fork 0
/
global.go
55 lines (48 loc) · 1.26 KB
/
global.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
package dyntpl
// Global describes value of global variable.
type Global any
type GlobalTuple struct {
docgen
val Global
}
var (
globIdx = map[string]int{}
globBuf []GlobalTuple
)
// RegisterGlobal registers new global variable.
//
// Caution! Globals registered after template parsing will take no effect.
func RegisterGlobal(name, alias string, val Global) *GlobalTuple {
if idx, ok := globIdx[name]; ok && idx >= 0 && idx < len(globBuf) {
return &globBuf[idx]
}
globBuf = append(globBuf, GlobalTuple{
docgen: docgen{name: name, typ: "any"},
val: val,
})
idx := len(globBuf) - 1
globIdx[name] = idx
if len(alias) > 0 {
globIdx[alias] = idx
}
return &globBuf[idx]
}
// RegisterGlobalNS registers new global variable in given namespace.
func RegisterGlobalNS(namespace, name, alias string, val Global) *GlobalTuple {
if len(namespace) == 0 {
return RegisterGlobal(name, alias, val)
}
name = namespace + "::" + name
if len(alias) > 0 {
alias = namespace + "::" + alias
}
return RegisterGlobal(name, alias, val)
}
// GetGlobal returns global variable by given name.
func GetGlobal(name string) Global {
if idx, ok := globIdx[name]; ok && idx >= 0 && idx < len(globBuf) {
return globBuf[idx].val
}
return nil
}
var _, _ = RegisterGlobalNS, GetGlobal