Golang Gin HTML模版使用

Gin支持HTML渲染來(lái)完成對(duì)于傳統(tǒng)MVC模式的支持。

以下是使用Gin框架渲染HTML模板的示例代碼:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    // 創(chuàng)建一個(gè)默認(rèn)的路由引擎
    router := gin.Default()

    // 設(shè)置HTML模板文件目錄
    router.LoadHTMLGlob("templates/*")

    // 定義路由
    router.GET("/", func(c *gin.Context) {
        // 渲染HTML模板
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Gin HTML模板示例",
        })
    })

    // 啟動(dòng)HTTP服務(wù)
    router.Run(":8080")
}

上述代碼中,router.LoadHTMLGlob 方法指定了HTML模板文件所在的目錄,該目錄下所有以.tmpl為擴(kuò)展名的文件都會(huì)被加載。

在路由處理函數(shù)中,可以使用c.HTML方法渲染HTML模板。該方法的第一個(gè)參數(shù)是HTTP狀態(tài)碼,第二個(gè)參數(shù)是模板文件的文件名,第三個(gè)參數(shù)是傳遞給模板的變量。在上述示例中,我們傳遞了一個(gè)變量title,其值為Gin HTML模板示例。

在模板文件中可以通過(guò){{ . }}語(yǔ)法來(lái)訪問(wèn)變量。例如,在上述示例中,可以使用{{ .title }}來(lái)訪問(wèn)title變量的值。

以下是一個(gè)簡(jiǎn)單的HTML模板示例:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ .title }}</title>
</head>
<body>
    <h1>{{ .title }}</h1>
</body>
</html>

上述模板文件中,{{ .title }}語(yǔ)法會(huì)被渲染成變量title的值。

模版有多種加載方式,還有通過(guò)LoadHTMLFiles方法加載HTML模板文件。

func main() {
    router := gin.Default()

    // 或者加載多個(gè)HTML模板文件
    router.LoadHTMLFiles("templates/index.tmpl", "templates/layout.tmpl")

    router.Run(":8080")
}

自定義模版布局

模板布局是指在多個(gè)HTML模板文件中公共部分的抽象表示??梢允褂?code>define和template模板函數(shù)來(lái)定義和使用模板布局。

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")

    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "首頁(yè)",
        })
    })

    router.GET("/about", func(c *gin.Context) {
        c.HTML(http.StatusOK, "about.tmpl", gin.H{
            "title": "關(guān)于我們",
        })
    })

    router.Run(":8080")
}

以下是index.tmplabout.tmpl的示例:

<!-- index.tmpl -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ .title }}</title>
</head>
<body>
    {{ template "content" . }}
</body>
</html>

<!-- about.tmpl -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ .title }}</title>
</head>
<body>
    {{ template "content" . }}
</body>
</html>
<!-- content.tmpl -->
{{ define "content" }}
<h1>{{ .title }}</h1>
{{ end }}

自定義模版函數(shù)

模版函數(shù)主要用于在模版中使用的,用于輔助頁(yè)面顯示的函數(shù),比如格式轉(zhuǎn)換等,例子如下

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

    "github.com/gin-gonic/gin"
)

func formatAsDate(t time.Time) string {
    year, month, day := t.Date()
    return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}

func main() {
    router := gin.Default()
    router.Delims("{[{", "}]}")
    router.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
    })
    router.LoadHTMLFiles("./testdata/template/raw.tmpl")

    router.GET("/raw", func(c *gin.Context) {
        c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
            "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
        })
    })

    router.Run(":8080")
}

raw.tmpl

Date: {[{.now | formatAsDate}]}

結(jié)果:

Date: 2017/07/01

自定義模版渲染器

Gin框架可以使用模板引擎來(lái)渲染HTML模板。常用的模板引擎有HTML/template、Mustache、Handlebars,下面是使用自定義的 html 模板渲染的例子

import "html/template"

func main() {
    router := gin.Default()
    html := template.Must(template.ParseFiles("file1", "file2"))
    router.SetHTMLTemplate(html)
    router.Run(":8080")
}

更復(fù)雜的例子

看以下代碼,它演示了使用Gin模板引擎渲染HTML模板,以及如何從模板獲取表單數(shù)據(jù):

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    // 首頁(yè)路由
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Gin Example",
        })
    })

    // 處理表單提交
    router.POST("/submit", func(c *gin.Context) {
        // 從POST表單獲取數(shù)據(jù)
        firstname := c.PostForm("firstname")
        lastname := c.PostForm("lastname")

        c.HTML(http.StatusOK, "submit.tmpl", gin.H{
            "firstname": firstname,
            "lastname":  lastname,
        })
    })

    router.Run(":8080")
}

其中,我們定義了兩個(gè)路由:一個(gè)是處理首頁(yè)請(qǐng)求,一個(gè)是處理表單提交請(qǐng)求。在首頁(yè)路由中,我們使用Gin的HTML方法渲染了一個(gè)名為"index.tmpl"的HTML模板,同時(shí)傳遞了一個(gè)變量"title"給模板。在表單提交路由中,我們使用PostForm方法從POST表單中獲取數(shù)據(jù),然后再將數(shù)據(jù)傳遞給名為"submit.tmpl"的HTML模板。

下面是"index.tmpl"和"submit.tmpl"的內(nèi)容:

<!-- index.tmpl -->
<!DOCTYPE html>
<html>
<head>
    <title>{{ .title }}</title>
</head>
<body>
    <h1>{{ .title }}</h1>
    <form action="/submit" method="POST">
        <label for="firstname">First Name:</label>
        <input type="text" name="firstname" id="firstname"><br><br>
        <label for="lastname">Last Name:</label>
        <input type="text" name="lastname" id="lastname"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

<!-- submit.tmpl -->
<!DOCTYPE html>
<html>
<head>
    <title>Form Submitted</title>
</head>
<body>
    <h1>Form Submitted</h1>
    <p>First Name: {{ .firstname }}</p>
    <p>Last Name: {{ .lastname }}</p>
</body>
</html>

以上示例代碼和HTML模板都可以用于參考和學(xué)習(xí)。當(dāng)然,在實(shí)際開(kāi)發(fā)中,需要根據(jù)具體的業(yè)務(wù)需求和情況進(jìn)行相應(yīng)的調(diào)整和改進(jìn)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容