3.1goweb框架gin下

Gin 框架有内置的模板引擎,它允许你将数据和 HTML 模板结合,动态生成网页内容。

模板引擎基础使用

单模板文件示例

以下是一个简单的使用单个 HTML 模板文件的示例,展示了如何在 Gin 中渲染模板:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

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

    // 加载单个模板文件
    r.LoadHTMLFiles("templates/index.html")

    r.GET("/", func(c *gin.Context) {
        // 渲染模板并传递数据
        c.HTML(http.StatusOK, "index.html", gin.H{
            "title": "Gin Template Example",
            "message": "Welcome to Gin's template engine!",
        })
    })

    r.Run(":8080")
}

对应的 templates/index.html 文件内容:

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

在上述代码中,LoadHTMLFiles 方法用于加载指定的 HTML 模板文件,c.HTML 方法用于渲染模板并向模板传递数据。

多模板文件及模板目录示例

如果有多个模板文件,可以使用 LoadHTMLGlob 方法加载整个目录下的模板文件:

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

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

    // 加载 templates 目录下的所有 HTML 模板文件
    r.LoadHTMLGlob("templates/**/*.html")

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "title": "Gin Multiple Templates Example",
            "message": "This is a multi - template example.",
        })
    })

    r.Run(":8080")
}

这里 LoadHTMLGlob 方法使用通配符 ** 来递归加载 templates 目录下的所有 HTML 文件。

模板语法

Gin 的模板引擎基于 Go 的标准模板库,支持以下常见语法:

  • 变量输出:使用 {{.VariableName}} 输出变量的值,如 {{.title}}
  • 条件判断
{{if .condition}}
    <p>Condition is true.</p>
{{else}}
    <p>Condition is false.</p>
{{end}}

  • 循环遍历
{{range .items}}
    <li>{{.}}</li>
{{end}}

模板继承

Gin 支持模板继承,允许你创建一个基础模板,然后在其他模板中继承和扩展它。

基础模板 templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{block "title" .}}Default Title{{end}}</title>
</head>
<body>
    <header>
        <h1>My Website</h1>
    </header>
    <main>
        {{block "content" .}}
            <p>Default content</p>
        {{end}}
    </main>
    <footer>
        <p>&copy; 2024 All rights reserved</p>
    </footer>
</body>
</html>
子模板 templates/index.html
{{define "title"}}Home Page{{end}}
{{define "content"}}
    <h2>Welcome to the Home Page</h2>
    <p>This is the home page content.</p>
{{end}}
Go 代码
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

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

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })

    r.Run(":8080")
}

在上述代码中,base.html 是基础模板,定义了网站的整体结构和一些默认内容,index.html 继承了 base.html 并覆盖了 title 和 content 块。

自定义模板函数

你可以向模板引擎中添加自定义函数,以满足特定的需求。

package main

import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)

// 自定义函数,将字符串转换为大写
func toUpper(s string) string {
    return template.HTMLEscapeString(strings.ToUpper(s))
}

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

    // 添加自定义函数
    r.SetFuncMap(template.FuncMap{
        "toUpper": toUpper,
    })
    r.LoadHTMLFiles("templates/index.html")

    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "text": "hello world",
        })
    })

    r.Run(":8080")
}

对应的 templates/index.html 文件可以使用这个自定义函数:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Custom Function Example</title>
</head>
<body>
    <p>{{toUpper .text}}</p>
</body>
</html>

模板包含

 Gin 框架里,你能够借助 Go 标准模板库的特性,让一个模板包含另一个模板,同时还能向包含的模板传递数据

  1. 模板定义:把要包含的模板单独定义好,且使用 {{define}} 标签来明确其名称。
  2. 加载模板:运用 LoadHTMLGlob 或者 LoadHTMLFiles 方法加载所有相关的模板文件。
  3. 包含模板:在主模板里使用 {{template}} 标签来包含其他模板,并且传递所需的数据。
  4. 渲染模板:在处理 HTTP 请求时,使用 c.HTML 方法渲染主模板。
package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

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

    // 加载 templates 目录下的所有 HTML 模板文件
    r.LoadHTMLGlob("templates/**/*.html")

    r.GET("/", func(c *gin.Context) {
        // 定义要传递的数据
        data := gin.H{
            "pageTitle": "Home Page",
            "headerTitle": "Welcome to My Website",
        }
        // 渲染 base.html 模板并传递数据
        c.HTML(http.StatusOK, "base.html", data)
    })

    r.Run(":8080")
}

 templates/base.html 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.pageTitle}}</title>
</head>
<body>
    <!-- 包含 header.html 模板并传递数据 -->
    {{template "header" .}}
    <main>
        <p>This is the main content of the page.</p>
    </main>
    <footer>
        <p>&copy; 2024 All rights reserved</p>
    </footer>
</body>
</html>

templates/header.html 文件 

{{define "header"}}
<header>
    <h1>{{.headerTitle}}</h1>
</header>
{{end}}
    • 利用 LoadHTMLGlob 方法加载 templates 目录下的所有 HTML 模板文件。
    • 定义了一个 HTTP GET 请求的处理函数,该函数会渲染 base.html 模板,并且传递一个包含 pageTitle 和 headerTitle 的数据对象。
  1. templates/header.html 文件

    • 运用 {{define "header"}} 标签定义了一个名为 header 的模板。
    • 该模板展示了一个包含 headerTitle 的标题。
  2. templates/base.html 文件

    • 采用 {{template "header" .}} 标签包含了名为 header 的模板,并将当前的数据对象传递给它。
    • 模板里还包含了页面的主要内容和页脚。

从前面的 Gin 框架示例(路由、中间件、模板引擎、文件上传下载等)可以看出,框架通过封装底层逻辑、提供标准化接口、抽象复杂操作等方式,显著简化了 Web 开发流程。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chxii

小小打赏,大大鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值