Displaying dynamic data
func (app *application) snippetView(w http.ResponseWriter, r *http.Request) { id, err := strconv.Atoi(r.PathValue("id")) if err != nil || id < 1 { http.NotFound(w, r) return } snippet, err := app.snippet.Get(id) if err != nil { if errors.Is(err, models.ErrNoRecord) { http.NotFound(w, r) } else { app.serverError(w, r, err) } return } // Initialize a slice containing the paths to the view.html file, // plus the base layout and navigation partial that we made earlier. files := []string{ "./ui/html/base.html", "./ui/html/partials/nav.html", "./ui/html/pages/view.html", } // Parse the template files. ts, err := template.ParseFiles(files...) if err != nil { app.serverError(w, r, err) return } // And then execute them. Notice how we are passing in the snippet // data (a models.Snippet struct) as the final parameter. err = ts.ExecuteTemplate(w, "base", snippet) if err != nil { app.serverError(w, r, err) } }
Any data that you pass as the final parameter to ts.ExecuteTemplate() is represented within your HTML templates by the . character (referred to as dot).
In this specific case, the underlying type of dot will be a models.Snippet struct. When the underlying type of dot is a struct, you can render (or yield) the value of any exported field in your templates by postfixing dot with the field name. So, because our models.Snippet struct has a Title field, we could yield the snippet title by writing {{.Title}} in our templates.
{{define "title"}}Snippet #{{.ID}}{{end}} {{define "main"}} <div class="snippet"> <div class="metadata"> <strong>{{.Title}}</strong> <span>#{{.ID}}</span> </div> <pre><code>{{.Content}}</code></pre> <div class="metadata"> <time>Created: {{.Created}}</time> <time>Expires: {{.Expires}}</time> </div> </div> {{end}}
标签:Web,struct,err,app,snippet,application,Snippet,html,Go From: https://www.cnblogs.com/zhangzhihui/p/18395336