我正在嘗試創建一個完整的堆疊應用程式,但我在模板部分遇到了問題。
只要頁面是靜態的,以下代碼就可以了,但是當我開始使用繼承函式(例如 {{template}}、{{define}} 或 {{block}})時會回傳一個空白頁面。
main.go :
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
fmt.Println("begin")
files := []string{
"layout.html",
"index.html",
}
tmpl, err := template.ParseFiles(files...)
if err != nil {
http.Error(rw, fmt.Sprintf("failed parsing template files | %s", err.Error()), http.StatusInternalServerError)
return
}
if err := tmpl.Execute(rw, nil); err != nil {
http.Error(rw, fmt.Sprintf("failed rendering template | %s", err.Error()), http.StatusInternalServerError)
return
}
}).Methods("GET")
if err := http.ListenAndServe(fmt.Sprintf(":3000"), router); err != nil {
log.Fatalf("failed starting server | %s", err.Error())
}
}
布局.html
{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<!-- bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title></title>
</head>
<body>
<main>
{{template "main" .}}
</main>
<!-- JQuery, Popper.js, Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X 965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH 8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM B07jRM" crossorigin="anonymous"></script>
</body>
</html>
{{end}}
索引.html
{{template "base" .}}
{{ define "main" }}
<h2>hello</h2>
<p>test</p>
{{ end }}
我已經從字面上復制了這些示例,但它仍然不起作用。我錯過了什么?
uj5u.com熱心網友回復:
ParseFiles回傳引數串列中第一個檔案的模板。檔案的模板是 {{define}}/{{end}} 塊之外的內容。
串列中的第一個檔案 layout.html 在 {{define}}/{{end}} 塊之外只有空格。
您需要檔案 index.html 中的模板。交換檔案的順序以解決問題。
files := []string{
"index.html",
"layout.html",
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/429127.html
