In my code, I’ve a layout
, a view
and a partial
templates.
I was able to load both the layout and view smoothly, now I’m addiing a new div
in a template called model
that is required to pop up once I clicked the button on the layout.
My code is:
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")
}()
Loading the template as:
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)
}
}
}
The templates themselves are:
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}}
Once I run the code, I got the error:
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"
I’m getting th eerror at this code block:
<script>
function showModel(){
{{template "model" .}}
}
</script>