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}}

    Condition is true.


    {{else}}

    Condition is false.


    {{end}}

  • 循环遍历

    {{range .items}}

  • {{.}}

  • {{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 并覆盖了 titlecontent 块。

自定义模板函数

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

复制代码
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 模板,并且传递一个包含 pageTitleheaderTitle 的数据对象。
  1. templates/header.html 文件

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

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

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

相关推荐
神奇侠20241 天前
快速开发-基于gin的中间件web项目开发
中间件·gin
Zyxalia5 天前
gin + es 实践 03
elasticsearch·jenkins·gin
Zyxalia5 天前
gin + es 实践 01
大数据·elasticsearch·gin
柯南二号5 天前
Go使用Gin写一个对MySQL的增删改查服务
mysql·golang·gin
Zyxalia6 天前
gin + es 实践 05
大数据·elasticsearch·gin
Zyxalia6 天前
gin + es 实践 07
网络·elasticsearch·gin
pedestrian_h9 天前
gRPC学习笔记记录以及整合gin开发
笔记·学习·golang·gin·grpc
liuyunshengsir12 天前
Gin 集成 prometheus 客户端实现注册和暴露指标
prometheus·gin
唐僧洗头爱飘柔952713 天前
(Go Gin)Gin学习笔记(三)数据解析和绑定:结构体分析,包括JSON解析、form解析、URL解析,区分绑定的Bind方法
golang·gin·数据绑定·数据解析·web开发框架·数据结构体分析
唐僧洗头爱飘柔952713 天前
(Go Gin)Gin学习笔记(二):路由配置、基本路由、表单参数、上传单个文件、上传多个文件、浅扒路由原理
学习·golang·gin·路由参数·路由配置·web开发框架·路由组