Go Web下gin框架的模板渲染的实现

 更新时间:2023年10月15日 12:10:09   作者:瑜陀  
Gin框架是目前非常流行的Go语言Web框架之一,作为一个轻量级的框架,Gin提供了丰富的功能和灵活的架构,本文就来介绍下Go Web下gin框架的模板渲染的实现,感兴趣的可以了解一下

脚本之家 / 编程助手:解决程序员“几乎”所有问题!
脚本之家官方知识库 → 点击立即使用

〇、前言

Gin框架是一个用于构建Web应用程序的轻量级Web框架,使用Go语言开发。它具有高性能、低内存占用和快速路由匹配的特点,旨在提供简单、快速的方式来开发可扩展的Web应用程序。
Gin框架的设计目标是保持简单和易于使用,同时提供足够的灵活性和扩展性,使开发人员能够根据项目的需求进行定制。它提供了许多有用的功能,如中间件支持、路由组、请求参数解析、模板渲染等,使开发人员能够快速构建高效的Web应用程序。

以下是Gin框架的一些主要特性:

  • 快速的性能:Gin框架采用了高性能的路由引擎,使请求路由匹配变得非常快速。

  • 中间件支持:Gin框架支持中间件机制,允许你在请求处理过程中添加自定义的中间件,用于处理认证、日志记录、错误处理等功能。

  • 路由组:Gin框架允许将路由按照逻辑组织成路由组,使代码结构更清晰,并且可以为不同的路由组添加不同的中间件。

  • 请求参数解析:Gin框架提供了方便的方法来解析请求中的参数,包括查询字符串参数、表单参数、JSON参数等。

  • 模板渲染:虽然Gin框架本身不提供模板引擎,但它与多种模板引擎库(如html/template、pongo2等)集成,使你能够方便地进行模板渲染。

  • 错误处理:Gin框架提供了内置的错误处理机制,可以捕获和处理应用程序中的错误,并返回适当的错误响应。

总体而言,Gin框架是一个简单、轻量级但功能强大的Web框架,非常适合构建高性能、可扩展的Web应用程序。它在Go语言社区中得到广泛的认可,并被许多开发人员用于构建各种类型的Web应用程序。

一、html/template

html/template是Go语言标准库中的一个包,用于生成和渲染HTML模板。它提供了一种安全且灵活的方式来生成HTML输出,支持模板继承、变量替换、条件语句、循环结构等功能。

html/template包的主要目标是防止常见的Web安全漏洞,如跨站脚本攻击(XSS)。它通过自动进行HTML转义和编码来确保生成的HTML是安全的,并防止恶意用户注入恶意代码。

使用html/template包可以将动态数据与静态HTML模板分离,使代码更易于维护和重用。你可以定义模板文件,然后将数据传递给模板进行渲染,最后生成最终的HTML输出。

(一)初次渲染

先创建一个名为 hello.tmpl的文件:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>Hello</title>
</head>
<body>
<p>hello, {{.}}</p>
</body>
</html>

这里的{{.}}中的.就代表了我们要填充的东东,接着创建我们的main.go函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main
 
import (
    "fmt"
    "html/template"
    "net/http"
)
 
func sayHello(w http.ResponseWriter, r *http.Request) {
    // 请勿刻舟求剑,用绝对地址
    t, err := template.ParseFiles("/Users/luliang/GoLand/gin_practice/chap1/hello.tmpl")
    if err != nil {
        fmt.Println("http server failed:%V", err)
        return
    }
    // 渲染模板
    err = t.Execute(w, "小王子!")
    if err != nil {
        fmt.Println("http server failed:%V", err)
        return
    }
}
func main() {
    http.HandleFunc("/hello", sayHello)
    err := http.ListenAndServe(":9000", nil)
    if err != nil {
        fmt.Println("http server failed:%V", err)
        return
    }
}

使用html/template进行HTML模板渲染的一般步骤如下:

  • 定义模板:
    首先,你需要定义HTML模板。可以在代码中直接定义模板字符串,也可以将模板保存在独立的文件中。比如我们创建了模板:hello.tmpl

  • 创建模板对象:
    使用template.New()函数创建一个模板对象。你可以选择为模板对象指定一个名称,以便在渲染过程中引用它。

  • 解析模板:
    使用模板对象的Parse()或ParseFiles()方法解析模板内容。如果模板内容保存在单独的文件中,可以使用ParseFiles()方法解析文件内容并关联到模板对象。

  • 渲染模板:
    创建一个用于存储模板数据的数据结构,并将数据传递给模板对象的Execute()方法。该方法将渲染模板并将结果写入指定的输出位置(如os.Stdout或http.ResponseWriter)。

在浏览器中输入:127.0.0.0:9000/hello就可以看到结果:hello, 小王子!

(二)传入其它数据进行渲染

上次渲染,我们用的是这一句:err = t.Execute(w, "小王子!"),可以看到我们传入了一个字符串而已。这次我们打算传点稍微不同的其它数据。继续编写模板test.tmpl:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>Hello</title>
</head>
<body>
<p>姓名: {{.Name}}</p>
<p>年龄: {{.Age}}</p>
<p>性别: {{.Gander}}</p>
</body>
</html>

可以看到,我们的模板稍微复杂起来了!继续编写 main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
 
import (
    "fmt"
    "html/template"
    "net/http"
)
 
type User struct {
    Name   string
    Gander string // 首字母是否大小写,作为是否对外暴露的标识
    Age    int
}
 
func sayHello(w http.ResponseWriter, r *http.Request) {
    // 定义模板
    u1 := User{
        Name:   "小王子",
        Gander: "男",
        Age:    19,
    }
    // 解析模板
    t, err := template.ParseFiles("/Users/luliang/GoLand/gin_practice/chap2/test.tmpl")
    if err != nil {
        fmt.Println("ParseFiles failed:%V", err)
        return
    }
    err = t.Execute(w, u1)
    if err != nil {
        return
    }
 
}
func main() {
    http.HandleFunc("/hello", sayHello)
    err := http.ListenAndServe(":9000", nil)
    if err != nil {
        fmt.Println("http server failed:%V", err)
        return
    }
 
}

可以看到我们在里面定义了一个结构类型 User,传入了一个 User 对象 u1:err = t.Execute(w, u1)

1
2
3
4
5
type User struct {
    Name   string
    Gander string // 首字母是否大小写,作为是否对外暴露的标识
    Age    int
}

赶紧看看运行结果,可以看到结果符合预期:

姓名: 小王子
年龄: 19
性别: 男

(三)定义函数参与渲染

定义我们的模板:f.tmpl:

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>hello</title>
</head>
<body>
{{ kua . }}
</body>
</html>

可以看到,我们的模板里面有一个函数名字叫做 kua,没错,这就是我们要的函数。

编写main.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main
import (
    "fmt"
    "html/template"
    "net/http"
)
func f(w http.ResponseWriter, r *http.Request) {
    // 定义模板
    k := func(name string) (string, error) {
        return name + "太棒了!", nil
    }
    t := template.New("f.tmpl")
    t.Funcs(template.FuncMap{
        "kua": k,
    })
    // 解析模板
    _, err := t.ParseFiles("/Users/luliang/GoLand/gin_practice/chap3/f.tmpl")
    if err != nil {
        return
    }
    // 渲染模板
    err = t.Execute(w, "小王子")
    if err != nil {
        return
    }
}
func main() {
    http.HandleFunc("/hello", f)
    err := http.ListenAndServe(":9002", nil)
    if err != nil {
        fmt.Println("http server failed:%V", err)
        return
    }
 
}

可以看到,我用了一个关键语句将函数kua 关联到了模板:

1
2
3
t.Funcs(template.FuncMap{
    "kua": k,
})

点击运行,可以看到结果:小王子太棒了!

(四)c.HTML() 渲染

在Gin框架中,可以使用c.HTML()方法来进行HTML模板渲染。该方法接收HTTP状态码、模板名称和渲染所需的数据作为参数。

编写模板index.tmpl:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>posts/index</title>
</head>
<body>
{{.title}}
</body>
</html>

可以看到我们只需渲染传入对象的 title 值,编写 main.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main
 
import (
    "github.com/gin-gonic/gin"
    "net/http"
)
 
func main() {
    r := gin.Default()
    r.LoadHTMLFiles("/Users/luliang/GoLand/gin_practice/chap4/index.tmpl")
    r.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "你好,前端真是太有意思了!",
        })
    })
    r.Run(":9091")
}

首先,创建一个 gin.default()路由对象,然后给该对象载入已经写好的模板文件,之后就可以用 GET 函数进行请求了。
先看看 GET 是什么东西:

1
2
3
4
// GET is a shortcut for router.Handle("GET", path, handlers).
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
    return group.handle(http.MethodGet, relativePath, handlers)
}

它说,GET 是router.Handle("GET", path, handlers)的一个捷径。再看看router.Handle("GET", path, handlers)是什么东西:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
    absolutePath := group.calculateAbsolutePath(relativePath)
    handlers = group.combineHandlers(handlers)
    group.engine.addRoute(httpMethod, absolutePath, handlers)
    return group.returnObj()
}
 
// Handle registers a new request handle and middleware with the given path and method.
// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.
// See the example code in GitHub.
//
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
// functions can be used.
//
// This function is intended for bulk loading and to allow the usage of less
// frequently used, non-standardized or custom methods (e.g. for internal
// communication with a proxy).

原来就是做了一下中间处理,注册了一个新的请求句柄。它还说GET, POST, PUT, PATCH、DELETE 都有类似的捷径。之后在 handlers中放一个匿名函数:

1
2
3
4
5
func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "你好,前端真是太有意思了!",
        })
    }

这个函数就是用于渲染的函数。猜测c.HTML()依然是一个 shortcut:

1
2
3
4
5
6
7
// HTML renders the HTTP template specified by its file name.
// It also updates the HTTP code and sets the Content-Type as "text/html".
// See http://golang.org/doc/articles/wiki/
func (c *Context) HTML(code int, name string, obj any) {
    instance := c.engine.HTMLRender.Instance(name, obj)
    c.Render(code, instance)
}

可以看到真正干活的还是 Render()

点击运行,结果为:你好,前端真是太有意思了!

(五)从多个模板中选择一个进行渲染

如果要渲染多个文件,该如何操作?比如我们通过输入不同的网站,服务器这时只需要选择不同的模板进行渲染就好。在这里创建了两个模板文件,users/index.tmpl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{{define "users/index.tmpl"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>users/index</title>
    </head>
    <body>
    {{.title}}
    </body>
    </html>
{{end}}

posts/index.tmpl:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{{define "posts/index.tmpl"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>posts/index</title>
    </head>
    <body>
    {{.title}}
    </body>
    </html>
{{end}}

这里使用了{{define "posts/index.tmpl"}}...{{end}}结构,对模板文件进行了命名。
编写main.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main
 
import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)
 
func main() {
    r := gin.Default()
     
    r.LoadHTMLGlob("/Users/luliang/GoLand/gin_practice/chap5/templates/**/*")
    r.GET("/posts/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "title": "posts/index.tmpl",
        })
    })
    r.GET("/users/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "title": "送你到百度!",
        })
    })
    r.Run(":9091")
}

我们在在浏览器地址栏输入http://127.0.0.1:9091/users/index可以得到:送你到百度!;而输入http://127.0.0.1:9091/posts/index可以得到:posts/index.tmpl

(六)加点东西,使得事情朝着有意思的方向进行!

我们为了使得网页画面更有趣,这里使用了多个文件,分别是index.css、index.js。编写:index.css:

1
2
3
body {
    background-color: #00a7d0;
}

没错只有一句话。接下来编写 index.js:

1
alert("Hello, Web!")

没错,也只有一句话。然后,我们把 css、js 文件引入到 index.tmpl中:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{{define "users/index.tmpl"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="/xxx/index.css" rel="external nofollow" >
        <title>users/index</title>
    </head>
    <body>
    {{.title}}
 
    <script src="/xxx/index.js"></script>
    </body>
    </html>
{{end}}

接下来写main.go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package main
 
import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)
 
func main() {
    r := gin.Default()
    // 加载静态文件
    r.Static("/xxx", "/Users/luliang/GoLand/gin_practice/chap5/statics")
     
    r.LoadHTMLGlob("/Users/luliang/GoLand/gin_practice/chap5/templates/**/*")
    r.GET("/posts/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "title": "posts/index.tmpl",
        })
    })
    r.GET("/users/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "title": "送你到百度!",
        })
    })
 
    r.Run(":9091")
}

因为我们要把 css、js 文件加载进去,因此要用 r.Static()函数把放置静态文件的目录加入进去。为了复用,第一个参数“/xxx”的意思是,只要index.tmpl文件中存在“/xxx”字段就直接指到我们设置的目录。
运行结果:首先 js 文件会首先渲染:

在这里插入图片描述

之后,css 文件会渲染:

在这里插入图片描述

可以看到这里出现了一个超链接,那是因为我们在这个字符后面插入了一个函数:

1
2
3
4
5
6
// 添加自定义函数
    r.SetFuncMap(template.FuncMap{
        "safe": func(str string) template.HTML {
            return template.HTML(str)
        },
    })

配合 index.tmpl,就可以了。

在这里插入图片描述

二、利用已有模板进行部署

通过以上的例子,终于学会了在模板中插入大量的css、js 进行渲染了!
首先找到某个网站,比如站长之家,下载一个模板:

在这里插入图片描述

选择第一个,下载之后解压:

在这里插入图片描述

static 外面的 index.html有用,其它都可以忽略。把 static 里面的文件夹复制到我们的工作目录:

同时,把 index.html文件复制到 posts(无所谓,强迫症而已),就可以使用了。

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

这样,在地址栏输入:http://127.0.0.1:9091/home,就可以看到效果了:

在这里插入图片描述

渲染的相当完美!这里会存在一些小细节,比如在 index.html文件中需要把 css、js文件的地址进行变更,变更到你放置这些文件的地址:

在这里插入图片描述

代码附上main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main
 
import (
    "github.com/gin-gonic/gin"
    "html/template"
    "net/http"
)
 
func main() {
    r := gin.Default()
    // 加载静态文件
    r.Static("/xxx", "/Users/luliang/GoLand/gin_practice/chap5/statics")
    // 添加自定义函数
    r.SetFuncMap(template.FuncMap{
        "safe": func(str string) template.HTML {
            return template.HTML(str)
        },
    })
    r.LoadHTMLGlob("/Users/luliang/GoLand/gin_practice/chap5/templates/**/*")
    r.GET("/posts/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "title": "posts/index.tmpl",
        })
    })
    r.GET("/users/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "title": "<a href='https://www.baidu.com'>送你到百度!</a>",
        })
    })
    r.GET("/home", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })
 
    r.Run(":9091")
}

这意味着,我们以后要想写网页,根本不需要进行大量的无意义的编程,利用 ChatGPT,我们可以写出大量的优秀的css、js 网页,我们要做的只是进行适量的改动,这将极大地丰富我们的创造力!

三、总结

本文从简单到难,对Go Web中 gin 框架下的模板渲染进行了简单的阐述。

到此这篇关于Go Web下gin框架的模板渲染的实现的文章就介绍到这了,更多相关Go  gin 模板渲染内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

蓄力AI

微信公众号搜索 “ 脚本之家 ” ,选择关注

程序猿的那些事、送书等活动等着你

原文链接:https://blog.csdn.net/m0_73651896/article/details/130834862

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请将相关资料发送至 reterry123@163.com 进行投诉反馈,一经查实,立即处理!

相关文章

  • Go语言中定时任务库Cron使用方法介绍

    Go语言中定时任务库Cron使用方法介绍

    cron的意思计划任务,说白了就是定时任务。我和系统约个时间,你在几点几分几秒或者每隔几分钟跑一个任务(job),今天通过本文给大家介绍下Go语言中定时任务库Cron使用方法,感兴趣的朋友一起看看吧
    2022-03-03
  • Golang实现基于时间的一次性密码TOTP

    Golang实现基于时间的一次性密码TOTP

    基于时间的一次性密码 TOTP 是 OTP 的一种实现方式,这种方法的优点是不依赖网络,因此即使在没有网络的情况下,用户也可以生成密码,下面我们就来看看如何使用golang实现一次性密码TOTP吧
    2023-11-11
  • Golang实现HTTP编程请求和响应

    Golang实现HTTP编程请求和响应

    本文主要介绍了Golang实现HTTP编程请求和响应,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-08-08
  • Go中的 = 和 := 区别小结

    Go中的 = 和 := 区别小结

    在Go语言编程中,"="用于给已声明的变量赋值,而":="同时声明并初始化变量,只能在函数内使用,理解这两者的不同,有助于编写更清晰的代码,下面就来介绍一下
    2024-10-10
  • VSCode Golang dlv调试数据截断问题及处理方法

    VSCode Golang dlv调试数据截断问题及处理方法

    这篇文章主要介绍了VSCode Golang dlv调试数据截断问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-06-06
  • Go变量作用域代码实战详解

    Go变量作用域代码实战详解

    Go语言提供了几种不同的作用域类型,使得开发者可以灵活地控制变量的可见范围和生命周期,本章节将详细概述Go语言中变量的各种作用域,帮助读者更好地理解和应用这些概念,需要的朋友可以参考下
    2024-06-06
  • 分享6个Go处理字符串的技巧小结

    分享6个Go处理字符串的技巧小结

    这篇文章主要介绍了分享6个Go处理字符串的技巧小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • 图文详解Go中的channel

    图文详解Go中的channel

    Channel是go语言内置的一个非常重要的特性,也是go并发编程的两大基石之一,下面这篇文章主要给大家介绍了关于Go中channel的相关资料,需要的朋友可以参考下
    2023-02-02
  • Go语言实现图片快递信息识别的简易方法

    Go语言实现图片快递信息识别的简易方法

    这篇文章主要为大家介绍了Go语言实现图片快递信息识别的简易方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • 深入解析Go语言中for循环的写法

    深入解析Go语言中for循环的写法

    这篇文章主要介绍了Go语言中for循环的写法,是Golang入门学习中的基础知识,需要的朋友可以参考下
    2015-10-10

最新评论