c 渲染html,HTML 渲染

使用 LoadHTMLGlob() 或者 LoadHTMLFiles()

```go

func main() {

router := gin.Default()

router.LoadHTMLGlob("templates/*")

//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")

router.GET("/index", func(c *gin.Context) {

c.HTML(http.StatusOK, "index.tmpl", gin.H{

"title": "Main website",

})

})

router.Run(":8080")

}

```

templates/index.tmpl

```html

{{ .title }}

```

使用不同目录下名称相同的模板

```go

func main() {

router := gin.Default()

router.LoadHTMLGlob("templates/**/*")

router.GET("/posts/index", func(c *gin.Context) {

c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{

"title": "Posts",

})

})

router.GET("/users/index", func(c *gin.Context) {

c.HTML(http.StatusOK, "users/index.tmpl", gin.H{

"title": "Users",

})

})

router.Run(":8080")

}

```

templates/posts/index.tmpl

```html

{{ define "posts/index.tmpl" }}

{{ .title }}

Using posts/index.tmpl

{{ end }}

```

templates/users/index.tmpl

```html

{{ define "users/index.tmpl" }}

{{ .title }}

Using users/index.tmpl

{{ end }}

```

#### 自定义模板渲染器

你可以使用自定义的 html 模板渲染

```go

import "html/template"

func main() {

router := gin.Default()

html := template.Must(template.ParseFiles("file1", "file2"))

router.SetHTMLTemplate(html)

router.Run(":8080")

}

```

#### 自定义分隔符

你可以使用自定义分隔

```go

r := gin.Default()

r.Delims("{[{", "}]}")

r.LoadHTMLGlob("/path/to/templates")

```

#### 自定义模板功能

查看详细[示例代码](https://github.com/gin-gonic/examples/tree/master/template)。

main.go

```go

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

```sh

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

```

结果:

```sh

Date: 2017/07/01

```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值