我有以下代碼:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"onsen/resources"
)
var view *template.Template
var err error
func init() {
fmt.Println("Starting up.")
view = template.Must(template.ParseFS(resources.Views, "templates/layouts/*.html", "templates/views/*.html", "templates/partials/*.html"))
if err != nil {
log.Fatal("Error loading templates:" err.Error())
}
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8070",
}
http.Handle("/webUI/", http.StripPrefix("/webUI/", http.FileServer(http.FS(resources.WebUI))))
http.HandleFunc("/process", process)
http.HandleFunc("/home", home)
http.HandleFunc("/test", test)
server.ListenAndServe()
}
在哪里onsen/resources:
package resources
import (
"embed"
)
// Views is our static web server layouts, views with dynamic content and partials content that is a static view.
//go:embed templates/layouts templates/views templates/partials
var Views embed.FS
路由功能是:
package main
import (
"log"
"net/http"
)
func home(w http.ResponseWriter, r *http.Request) {
err = view.ExecuteTemplate(w, "home.html", nil)
if err != nil {
log.Fatalln(err)
}
}
func test(w http.ResponseWriter, r *http.Request) {
err = view.ExecuteTemplate(w, "test.html", nil)
if err != nil {
log.Fatalln(err)
}
}
func process(w http.ResponseWriter, r *http.Request) {
err = view.ExecuteTemplate(w, "process.html", nil)
if err != nil {
log.Fatalln(err)
}
}
我的模板是:
base.html
<!-- Content of base.html: -->
{{define "base"}}
<!doctype html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta charset="utf-8">
</head>
<body>
{{template "content" .}}
</body>
</html>
{{end}}
意見是:
<!-- Content of home.html: -->
{{template "base" .}}
{{define "content"}}
This is home
{{end}}
和;
<!-- Content of test.html: -->
{{template "base" .}}
{{define "content"}}
test file is here
{{end}}
和
<!-- Content of process.html: -->
{{template "base" .}}
{{define "content"}}
process goes here
{{end}}
但是所有路線都顯示相同的結果,與模板相同 test.html

我在我的模板結構中提到了這個,但看起來與嵌入有關!
uj5u.com熱心網友回復:
感謝Cerise的評論
應用程式將所有模板檔案決議為一個模板集。test.html 中的“內容”模板是要添加到集合中的最后一個“內容”模板。這是您在每一頁上看到的那個。將每個頁面的模板決議為單獨的集合。
所以,這里是正確的作業代碼
package main
import (
"html/template"
"log"
"net/http"
"onsen/resources"
)
func process(w http.ResponseWriter, r *http.Request) {
view := template.Must(template.ParseFS(resources.Views, "templates/layouts/base.html", "templates/views/other.html", "templates/partials/*.html"))
type approval struct {
Status bool
}
workflow := approval{Status: false}
err = view.ExecuteTemplate(w, "process.html", workflow)
if err != nil {
log.Fatalln(err)
}
}
模板process.html是:
<!-- Content of other.html: -->
{{template "base" .}}
{{define "content"}}
process goes here
{{ .Status }}
{{if .Status}}
{{template "approved"}}
{{else}}
{{template "rejected"}}
{{end}}
{{end}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338496.html
標籤:走
上一篇:包名和變數是否應該避免陰影?
下一篇:無法呼叫嵌入的css/js檔案
