forked from a-h/templ
-
Notifications
You must be signed in to change notification settings - Fork 0
/
textparser.go
47 lines (39 loc) · 1021 Bytes
/
textparser.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
package parser
import (
"unicode"
"github.com/a-h/parse"
)
var tagTemplOrNewLine = parse.Any(parse.Rune('<'), parse.Rune('{'), parse.Rune('}'), parse.String("\r\n"), parse.Rune('\n'))
var textParser = parse.Func(func(pi *parse.Input) (n Node, ok bool, err error) {
from := pi.Position()
// Read until a tag or templ expression opens.
var t Text
if t.Value, ok, err = parse.StringUntil(tagTemplOrNewLine).Parse(pi); err != nil || !ok {
return
}
if isWhitespace(t.Value) {
return t, false, nil
}
if _, ok = pi.Peek(1); !ok {
err = parse.Error("textParser: unterminated text, expected tag open, templ expression open, or newline", from)
return
}
// Parse trailing whitespace.
ws, _, err := parse.Whitespace.Parse(pi)
if err != nil {
return t, false, err
}
t.TrailingSpace, err = NewTrailingSpace(ws)
if err != nil {
return t, false, err
}
return t, true, nil
})
func isWhitespace(s string) bool {
for _, r := range s {
if !unicode.IsSpace(r) {
return false
}
}
return true
}