2017-08-06 09:02:39 +02:00
|
|
|
package html
|
|
|
|
|
|
|
|
import . "github.com/vektah/goparsify"
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
func Parse(input string) (result interface{}, remaining string, err error) {
|
2017-08-06 09:02:39 +02:00
|
|
|
return ParseString(tag, input)
|
|
|
|
}
|
|
|
|
|
|
|
|
type Tag struct {
|
|
|
|
Name string
|
|
|
|
Attributes map[string]string
|
2017-08-06 15:32:10 +02:00
|
|
|
Body []interface{}
|
2017-08-06 09:02:39 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
tag Parser
|
|
|
|
|
2017-08-06 15:32:10 +02:00
|
|
|
identifier = Merge(And(Chars("a-z", 1, 1), Chars("a-zA-Z0-9", 0)))
|
2017-08-07 10:25:23 +02:00
|
|
|
text = Map(NotChars("<>"), func(n *Node) *Node {
|
|
|
|
return &Node{Result: n.Token}
|
|
|
|
})
|
2017-08-06 09:02:39 +02:00
|
|
|
|
|
|
|
element = Any(text, &tag)
|
2017-08-07 10:25:23 +02:00
|
|
|
elements = Map(Kleene(element), func(n *Node) *Node {
|
|
|
|
ret := []interface{}{}
|
|
|
|
for _, child := range n.Children {
|
|
|
|
ret = append(ret, child.Result)
|
|
|
|
}
|
|
|
|
return &Node{Result: ret}
|
|
|
|
})
|
|
|
|
|
2017-08-06 09:28:34 +02:00
|
|
|
attr = And(WS, identifier, WS, "=", WS, Any(String('"'), String('\'')))
|
2017-08-07 10:25:23 +02:00
|
|
|
attrs = Map(Kleene(attr, WS), func(node *Node) *Node {
|
2017-08-06 09:02:39 +02:00
|
|
|
attr := map[string]string{}
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
for _, attrNode := range node.Children {
|
|
|
|
attr[attrNode.Children[0].Token] = attrNode.Children[2].Token
|
2017-08-06 09:02:39 +02:00
|
|
|
}
|
|
|
|
|
2017-08-07 10:25:23 +02:00
|
|
|
return &Node{Result: attr}
|
2017-08-06 09:02:39 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
tstart = And("<", identifier, attrs, ">")
|
|
|
|
tend = And("</", identifier, ">")
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
2017-08-07 10:25:23 +02:00
|
|
|
tag = Map(And(tstart, elements, tend), func(node *Node) *Node {
|
|
|
|
openTag := node.Children[0]
|
|
|
|
return &Node{Result: Tag{
|
|
|
|
Name: openTag.Children[1].Token,
|
|
|
|
Attributes: openTag.Children[2].Result.(map[string]string),
|
|
|
|
Body: node.Children[1].Result.([]interface{}),
|
|
|
|
}}
|
2017-08-06 09:02:39 +02:00
|
|
|
|
|
|
|
})
|
|
|
|
}
|