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 开发流程。

相关推荐
Delphi菜鸟2 天前
go+mysql+cocos实现游戏搭建
mysql·游戏·golang·gin·cocos2d
老朋友此林6 天前
go语言学习笔记:gin + gorm + mysql 用户增删改查案例入门
mysql·golang·gin
梦兮林夕8 天前
06 文件上传从入门到实战:基于Gin的服务端实现(一)
后端·go·gin
能来帮帮蒟蒻吗20 天前
GO语言学习(16)Gin后端框架
开发语言·笔记·学习·golang·gin
Json201131520 天前
Gin、Echo 和 Beego三个 Go 语言 Web 框架的核心区别及各自的优缺点分析,结合其设计目标、功能特性与适用场景
前端·golang·gin·beego
Json201131521 天前
Swoole 的 Hyperf 框架和 Go 的 Gin 框架高并发原理以及技术实现对比分析
网络·php·gin·swoole
赴前尘21 天前
Go+Gin实现安全多文件上传:带MD5校验的完整解决方案
安全·golang·gin
Golinie21 天前
Ollama+Langchaingo+Gin开发本地LLM简单应用
大模型·gin·ollama·langchaingo
yuanlaile22 天前
Gin介绍及Gin环境搭建
golang·gin·gin环境搭建