iT邦幫忙

2021 iThome 鐵人賽

DAY 22
0
自我挑戰組

go go let's go - golang 從0開始系列 第 22

Golang 轉生到web世界 - Gin HTML渲染

Golang

Gin HTML渲染

首先我們需要在程式碼所在的資料夾下,建立一個view的資料夾,並且在該資料夾下建立一個簡單的html檔案。

<html>
    <h1>
        {{ .title }}
    </h1>
</html>

這個{{ }} 應該不陌生啦!

使用 LoadHTMLGlob ()來讀取html所在的位置(所以LoadHTMLGlob所指定的資料夾名稱需要跟自己建立的相同),c.HTML 所指定hello.html必須是要跟html檔案相呼應。

package main

import (
	"net/http"

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

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("view/*")
	router.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "hello.html", gin.H{
			"title": "hello~ html",
		})
	})

	router.Run(":8000")
}

我們也可以有多層結構的做法
router.LoadHTMLGlob("templates/**/*")

當然route也可以做多個來使用囉

package main

import (
	"net/http"

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

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("view/**/*")
	router.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "users/user.html", gin.H{
			"title": "hello",
		})
	})
	router.GET("/users/index2", func(c *gin.Context) {
		c.HTML(http.StatusOK, "users/user.html", gin.H{
			"title": "Users",
		})
	})
	router.Run(":8000")
}

但這邊要注意的是如果有用多層的話,HTML的內容需要調整一下
必須要加上,要特別注意的是他是開頭跟結尾夾著,這部分我一開始沒注意到有結尾的end,導致跑不出來。缺一不可唷
{{ define "users/user.html" }} …. {{ end }}

否則會報錯唷
參考如下:

{{ define "users/user.html" }}
<html>
    <h1>
        {{ .title }} user
    </h1>
</html>
{{ end }}

上一篇
Golang 轉生到web世界 - gin路由
下一篇
Golang 轉生到web世界 - gin Middleware中間件
系列文
go go let's go - golang 從0開始30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言