Просмотр исходного кода

page injector: add skipDefaultSetting

xuxin 1 год назад
Родитель
Сommit
8f5a70b179
4 измененных файлов с 31 добавлено и 15 удалено
  1. 5 0
      extract_test.go
  2. 1 3
      page.go
  3. 24 12
      page_injector.go
  4. 1 0
      page_injector_test.go

+ 5 - 0
extract_test.go

@@ -0,0 +1,5 @@
+package web
+
+func SetDefault(pi *PageInjector, pageTitle string) {
+	pi.setDefault(pageTitle)
+}

+ 1 - 3
page.go

@@ -119,9 +119,7 @@ func (p *PageBuilder) index(w http.ResponseWriter, r *http.Request) {
 	c := WrapEventContext(r.Context(), ctx)
 	pr, body := p.render(w, r, c, head)
 
-	if len(pr.PageTitle) > 0 {
-		head.Title(pr.PageTitle)
-	}
+	head.setDefault(pr.PageTitle)
 
 	var resp string
 	resp, err = p.b.layoutFunc(r, head, body)

+ 24 - 12
page_injector.go

@@ -20,8 +20,9 @@ type keyComp struct {
 }
 
 type PageInjector struct {
-	comps map[injectPosition][]*keyComp
-	lang  string
+	skipDefaultSetting bool
+	comps              map[injectPosition][]*keyComp
+	lang               string
 }
 
 type injectPosition int
@@ -60,6 +61,27 @@ func (b *PageInjector) getComp(key interface{}, pos injectPosition) *keyComp {
 	return nil
 }
 
+// SkipDefaultSetting skips the setting of default nodes
+func (b *PageInjector) SkipDefaultSetting() {
+	b.skipDefaultSetting = true
+}
+
+func (b *PageInjector) setDefault(pageTitle string) {
+	if b.skipDefaultSetting {
+		return
+	}
+
+	if !b.HasTitle() && len(pageTitle) > 0 {
+		b.Title(pageTitle)
+	}
+	if b.getComp(MetaKey("charset"), head) == nil {
+		b.Meta(MetaKey("charset"), "charset", "utf8")
+	}
+	if b.getComp(MetaKey("viewport"), head) == nil {
+		b.MetaNameContent("viewport", "width=device-width, initial-scale=1, shrink-to-fit=no")
+	}
+}
+
 func (b *PageInjector) Title(title string) {
 	b.addNode(h.Title(""), titleKey, true, title)
 	return
@@ -113,7 +135,6 @@ func toHTMLComponent(list []*keyComp) h.HTMLComponent {
 }
 
 func (b *PageInjector) GetHeadHTMLComponent() h.HTMLComponent {
-	b.addCharsetViewPortIfMissing()
 	return toHTMLComponent(b.comps[head])
 }
 
@@ -134,15 +155,6 @@ func (b *PageInjector) GetHTMLLang() string {
 	return b.lang
 }
 
-func (b *PageInjector) addCharsetViewPortIfMissing() {
-	if b.getComp(MetaKey("charset"), head) == nil {
-		b.Meta(MetaKey("charset"), "charset", "utf8")
-	}
-	if b.getComp(MetaKey("viewport"), head) == nil {
-		b.MetaNameContent("viewport", "width=device-width, initial-scale=1, shrink-to-fit=no")
-	}
-}
-
 func (b *PageInjector) addNode(tag *h.HTMLTagBuilder, key interface{}, replace bool, body string, attrs ...string) {
 	l := len(attrs)
 	if l%2 != 0 {

+ 1 - 0
page_injector_test.go

@@ -97,6 +97,7 @@ func TestDefaultPageInjector(t *testing.T) {
 
 			var b web.PageInjector
 			c.operation(&b)
+			web.SetDefault(&b, "")
 			diff := testingutils.PrettyJsonDiff(
 				strings.TrimSpace(c.expected),
 				strings.TrimSpace(h.MustString(b.GetHeadHTMLComponent(), context.TODO())))