Go中加载多个模板的方法

105 阅读1分钟

在我的代码中,我有一个layout ,一个view 和一个partial 的模板。
我能够顺利地加载布局和视图,现在我在一个叫做model 的模板中添加了一个新的div ,一旦我点击布局上的按钮,就需要弹出。

我的代码是

import (
	"embed"
)

//go:embed libs/scripts layouts views partials scripts styles
var Views embed.FS

func Run(port string) {
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(Views))))

	http.HandleFunc("/messages/", messages)

	http.ListenAndServe(port, nil)
}

func main() {
	go func() {
		Run(":1235")
		println("server closed")
	}()

加载模板为。

func messages(w http.ResponseWriter, r *http.Request) {

	if tmpl, err := template.ParseFS(Views,
		"layouts/base.html",
		"views/messages.html",
		"partials/model.html"); err != nil {
		fmt.Println("Error in file parsing:", err)
	} else {
		err = tmpl.ExecuteTemplate(w, "messages.html", nil)
		if err != nil {
			fmt.Println("error executing the template:", err)
		}
	}
}

模板本身是:
partials/model.html

{{define "model"}}
<link rel="stylesheet" href="http://localhost:1235/static/styles/model.css">
<div id="modal1" class="overlay">
	<a class="cancel" href="#"></a>
	<div class="modal">
		<h2>This is Modal Overlay 1</h2>
		<div class="content">
			<p>Click outside the modal to close.</p>
		</div>
	</div>
</div>
{{end}}

views/messages.html:


<!-- messages -->
{{template "base" .}}
{{define "body"}}

<body>

<div></div>

<script src="http://localhost:1235/static/scripts/messages.js" charset="utf-8" type="text/javascript"></script>

</body>
</html>
{{end}}

layouts/base.html:

<!-- base layout -->
{{define "base"}}
<!DOCTYPE html>
<html lang="ar-AR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>WhatsApp</title>
  <link rel="stylesheet" href="http://localhost:1235/static/styles/style.css">
</head>

<body>
<button type="button" onClick="showModel()">
   Send
</button>
        {{template "body" .}}
</body>
<script>
  function showModel(){
    {{template "model" .}}
  }
</script>
</html>
{{end}}

一旦我运行该代码,我得到了错误。

error executing the template: html/template:base.html:20:15: no such template "model"
error executing the template: html/template:base.html:20:15: no such template "model"

我在这个代码块上得到了这个错误。

<script>
  function showModel(){
    {{template "model" .}}
  }
</script>