模板渲染

基本模板

使用html/template包渲染基本HTML模板。

package main

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

type PageData struct {
    Title string
    Content string
}

func handler(w http.ResponseWriter, r *http.Request) {
    // 解析模板
    tmpl := template.Must(template.ParseFiles("templates/layout.html"))
    
    // 准备数据
    data := PageData{
        Title: "首页",
        Content: "欢迎访问我们的网站!",
    }
    
    // 渲染模板
    tmpl.Execute(w, data)
}

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

模板嵌套

使用模板嵌套实现页面布局。

// layout.html



    {{.Title}}


    {{template "header" .}}
    {{template "content" .}}
    {{template "footer" .}}



// header.html
{{define "header"}}

{{.Title}}

{{end}} // content.html {{define "content"}}

{{.Content}}

{{end}} // footer.html {{define "footer"}}

© 2024 Go语言学习指南

{{end}}

模板函数

使用自定义函数扩展模板功能。

package main

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

func formatDate(t time.Time) string {
    return t.Format("2006-01-02")
}

func main() {
    // 创建函数映射
    funcMap := template.FuncMap{
        "formatDate": formatDate,
    }
    
    // 解析模板
    tmpl := template.Must(template.New("").Funcs(funcMap).ParseFiles("templates/post.html"))
    
    // 准备数据
    data := struct {
        Title string
        Date  time.Time
    }{
        Title: "Go语言学习",
        Date:  time.Now(),
    }
    
    // 渲染模板
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl.Execute(w, data)
    })
    
    http.ListenAndServe(":8080", nil)
}

条件渲染

在模板中使用条件语句。

// template.html



    {{.Title}}


    {{if .User}}
        

欢迎回来,{{.User.Name}}!

退出 {{else}}

登录

{{end}} {{if .Posts}}

文章列表

{{range .Posts}}

{{.Title}}

{{.Content}}

{{if .Published}} 已发布 {{else}} 草稿 {{end}}
{{end}} {{else}}

暂无文章

{{end}}

循环渲染

在模板中使用循环语句。

// template.html



    {{.Title}}


    

{{.Title}}

    {{range .Items}}
  • {{.Name}} - {{.Price}}
  • {{end}}
{{range $index, $item := .Items}} {{end}}
ID 名称 价格
{{$index}} {{$item.Name}} {{$item.Price}}