go框架gin(下)

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

模板引擎基础使用

单模板文件示例

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

go 复制代码
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 文件内容:

xml 复制代码
<!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 方法加载整个目录下的模板文件:

go 复制代码
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}}
  • 条件判断
vbnet 复制代码
{{if .condition}}
    <p>Condition is true.</p>
{{else}}
    <p>Condition is false.</p>
{{end}}
  • 循环遍历
css 复制代码
{{range .items}}
    <li>{{.}}</li>
{{end}}

模板继承

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

基础模板 templates/base.html

xml 复制代码
<!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

arduino 复制代码
{{template "base.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 代码

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 块。

自定义模板函数

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

go 复制代码
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 文件可以使用这个自定义函数:

xml 复制代码
<!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 方法渲染主模板。
go 复制代码
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 文件

xml 复制代码
<!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 文件

css 复制代码
{{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 开发流程。

相关推荐
郭京京2 小时前
go框架gin(中)
后端·go
林树的编程频道2 小时前
单例模式的推导
后端
就是帅我不改2 小时前
揭秘Netty高性能HTTP客户端:NIO编程的艺术与实践
后端·面试·github
Ray662 小时前
SugLucene索引构建
后端
舒一笑2 小时前
Saga分布式事务框架执行逻辑
后端·程序员·设计
Emma歌小白3 小时前
完整后台模块模板
后端
得物技术3 小时前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
Emma歌小白3 小时前
配套后端(Node.js + Express + SQLite)
后端
isysc13 小时前
面了一个校招生,竟然说我是老古董
java·后端·面试