Refactor document creation in build.go and parser.go

This commit is contained in:
Max 2024-01-10 13:20:22 +08:00
parent cec9a2cbd0
commit 669ccfb1e1
3 changed files with 32 additions and 11 deletions

View file

@ -25,7 +25,7 @@ func (page *Page) Build(option *BuildOption) (*goquery.Document, []string, error
}
// Add Style & Script & Warning
doc, err := NewDocument([]byte(html))
doc, err := NewDocumentString(html)
if err != nil {
warnings = append(warnings, err.Error())
}
@ -81,7 +81,7 @@ func (page *Page) BuildForImport(option *BuildOption, slots map[string]interface
}
// Add Style & Script & Warning
doc, err := NewDocument([]byte(html))
doc, err := NewDocumentString(html)
if err != nil {
warnings = append(warnings, err.Error())
}
@ -121,7 +121,21 @@ func (page *Page) BuildForImport(option *BuildOption, slots map[string]interface
}
func (page *Page) parse(doc *goquery.Document, option *BuildOption, warnings []string) error {
pages := doc.Find("page")
pages := doc.Find("*").FilterFunction(func(i int, sel *goquery.Selection) bool {
tagName := sel.Get(0).Data
if tagName == "page" {
return true
}
if tagName == "slot" {
return false
}
_, has := sel.Attr("is")
return has
})
sui := SUIs[page.SuiID]
if sui == nil {
return fmt.Errorf("SUI %s not found", page.SuiID)

View file

@ -1,7 +1,6 @@
package core
import (
"bytes"
"fmt"
"strings"
@ -58,8 +57,7 @@ func (parser *TemplateParser) Render(html string) (string, error) {
html = fmt.Sprintf(`<!DOCTYPE html><html lang="en">%s</html>`, html)
}
reader := bytes.NewReader([]byte(html))
doc, err := goquery.NewDocumentFromReader(reader)
doc, err := NewDocumentString(html)
if err != nil {
return "", err
}
@ -145,7 +143,7 @@ func (parser *TemplateParser) parseElementNode(sel *goquery.Selection) {
parser.forStatementNode(sel)
}
if sel.Get(0).Data == "s:set" {
if _, exist := sel.Attr("s:set"); exist || sel.Get(0).Data == "s:set" {
parser.setStatementNode(sel)
}

View file

@ -5,14 +5,23 @@ import (
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/net/html"
)
// NewDocument create a new document
func NewDocument(html []byte) (*goquery.Document, error) {
return goquery.NewDocumentFromReader(bytes.NewReader(html))
func NewDocument(htmlContent []byte) (*goquery.Document, error) {
docNode, err := html.Parse(bytes.NewReader(htmlContent))
if err != nil {
return nil, err
}
return goquery.NewDocumentFromNode(docNode), nil
}
// NewDocumentString create a new document
func NewDocumentString(html string) (*goquery.Document, error) {
return goquery.NewDocumentFromReader(strings.NewReader(html))
func NewDocumentString(htmlContent string) (*goquery.Document, error) {
docNode, err := html.Parse(strings.NewReader(htmlContent))
if err != nil {
return nil, err
}
return goquery.NewDocumentFromNode(docNode), nil
}