forked from karlseguin/gerb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output.go
54 lines (48 loc) · 1 KB
/
output.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
package gerb
import (
"bytes"
"github.com/karlseguin/gerb/core"
"github.com/karlseguin/gerb/r"
)
type OutputTag struct {
value core.Value
autoEscape bool
}
func (o *OutputTag) Execute(context *core.Context) core.ExecutionState {
value := r.ToBytes(o.value.Resolve(context))
if o.autoEscape {
value = escape(value)
}
context.Writer.Write(r.ToBytes(value))
return core.NormalState
}
func createOutputTag(p *core.Parser, isUnsafe bool) (core.Executable, error) {
value, err := p.ReadValue()
if err != nil {
return nil, err
}
if err = p.ReadCloseTag(); err != nil {
return nil, err
}
return &OutputTag{value, !isUnsafe}, nil
}
const escapedChars = "<>"
func escape(b []byte) []byte {
var buf bytes.Buffer
i := bytes.IndexAny(b, escapedChars)
for i != -1 {
buf.Write(b[:i])
var esc []byte
switch b[i] {
case '<':
esc = []byte("<")
case '>':
esc = []byte(">")
}
b = b[i+1:]
buf.Write(esc)
i = bytes.IndexAny(b, escapedChars)
}
buf.Write(b)
return buf.Bytes()
}