返回介绍

HTML Templates

发布于 2025-02-25 22:26:26 字数 1964 浏览 0 评论 0 收藏 0

Serving HTML is an important job for some web applications. Go has one of my favorite templating languages to date. Not for its features, but for its simplicity and out of the box security. Rendering HTML templates is almost as easy as rendering JSON using the 'html/template' package from the standard library. Here is what the source code for rendering HTML templates looks like:

package main

import (
  "html/template"
  "net/http"
  "path"
)

type Book struct {
  Title  string
  Author string
}

func main() {
  http.HandleFunc("/", ShowBooks)
  http.ListenAndServe(":8080", nil)
}

func ShowBooks(w http.ResponseWriter, r *http.Request) {
  book := Book{"Building Web Apps with Go", "Jeremy Saenz"}

  fp := path.Join("templates", "index.html")
  tmpl, err := template.ParseFiles(fp)
  if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
  }

  if err := tmpl.Execute(w, book); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}

This is the following template we will be using. It should be placed in a templates/index.html file in the directory your program is run from:

<html>
  <h1>{{ .Title }}</h1>
  <h3>by {{ .Author }}</h3>
</html>

Exercises

  1. Look through the docs for text/template and html/template package. Play with the templating language a bit to get a feel for its goals, strengths, and weaknesses.
  2. In the example we parse the files on every request, which can be a lot of performance overhead. Experiment with parsing the files at the beginning of your program and executing them in your http.Handler (hint: make use of the Copy() method on html.Template ).
  3. Experiment with parsing and using multiple templates.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文