The gin framework in Go language learns custom template functions for template rendering (4)

How to customize template functions in gin framework.

In the gin framework, we can use the html/template module that comes with the Go language for template rendering.
The html/template module provides a series of built-in functions, such as eq, ne, and, or, etc., but sometimes we need to customize some functions to meet our needs, such as calculating the MD5 value of a string.

We can register custom functions into the template engine through the SetFuncMap method so that they can be used in templates. This method receives a parameter of type FuncMap, which is a mapping table in which the key is the name of the custom function and the value is the custom function itself. In this way, we can call custom functions through the function name in the template to achieve some special functions.

The usage scenarios of custom template functions are very wide. For example, we can define a function that formats time, converts the timestamp into a human-readable format, or defines a function that calculates the length of a string to help us add some characters in the template. String operations and so on.

Let's take a look at how to customize template functions in the gin framework. Let's share two cases. One is one I used in my study, and the other is a case I saw online;

Case 1: Define a function that formats time

Defined in the main.go main entry file, a custom template function is required;

package main

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

// 定一个函数,这里就是我们自定义的函数了

func UnitTime(timestamp int) string {
	t := time.Unix(int64(timestamp), 0)

	return t.Format("2006-01-02 15:09:01")
}

func main() {
	// 定义一个路由引擎
	r := gin.Default()

	//自定义函数 渲染 注入模版 使用 router.SetFuncMap(template.FuncMap{}) 这个里面用到的包"html/template",就是一个第三方自定义函数包名称,负责渲染模版函数template到html内;
	r.SetFuncMap(template.FuncMap{
		"UnitTime": UnitTime,
	})

    // 加载 渲染模版
    r.LoadHTMLGlob("*templates/**/*")


    // 创建 路由
    r.GET("/", func(ctx *gin.Context) {

		new := &Article{
			Title:   "admin/index",
			Content: "这是一个首页后台管理",
		}
		ctx.HTML(http.StatusOK, "default/index.html", gin.H{
			"title": "首页",
			"msg":   "lll",
			"news":  new,
			"score": 100,
			"list":  []string{"吃饭", "睡觉", "写代码"}, // 数组
			"scoreList": []interface{}{
				&Article{
					Title:   "新闻一",
					Content: "新闻内容11111",
				},
				&Article{
					Title:   "新闻二",
					Content: "新闻内容2222",
				},
			},
			"data": 1686593382, //时间戳
		})

	})
	

	//启动服务
	r.Run(":8001")
}

 At the same time, we need to use it in the template templates/default/index.html. The following is the html usage code:

{
   
   { define "default/index.html" }}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>default/index.html</title>
    <link rel="stylesheet" href="/static/css/index.css">
</head>

<body>
    <h2>实际开发常用函数,自定义函数 </h2>
    <p>
        {
   
   {UnitTime .data }}
    </p>
    <p style="font-size:14px;color: red;">{
   
   {.data | UnitTime}}</p>

</body>
</html>
{
   
   {end}}

Note⚠️The " html/template " package here, " html/template " is a package in the Go language standard library, used to generate HTML pages. It provides a secure way to render dynamic data, avoiding common XSS (cross-site scripting) vulnerabilities. In a template, you can use variables, control structures, functions, etc. to organize the structure and content of the page.

Note : "html/template" is a package in the Go language standard library, used to generate HTML pages. It provides a secure way to render dynamic data, avoiding common XSS (cross-site scripting) vulnerabilities. In a template, you can use variables, control structures, functions, etc. to organize the structure and content of the page. At the same time, "html/template" also supports advanced features such as template inheritance, partial templates, and pipelines, which can help us build complex HTML pages more easily.

Case 2: Define an encryption function


First, create a file named funcMap.go in our project to store our custom template functions. The code is as follows:

package main

import (
    "crypto/md5"
    "encoding/hex"
    "html/template"
)

// 定义一个计算字符串MD5值的函数
func md5V(str string) string {
    h := md5.New()
    h.Write([]byte(str))
    return hex.EncodeToString(h.Sum(nil))
}

// 初始化自定义函数
func InitFuncMap() template.FuncMap {
    funcMap := template.FuncMap{
        "md5": md5V,
    }
    return funcMap
}

In the above code, we define a function named md5V to calculate the MD5 value of a string. Then we initialize our custom function md5 through the
InitFuncMap function and put it into template.FuncMap.

Next, use the custom function in our template file, the code is as follows:


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{
   
   {.Title}}</title>
</head>
<body>
    <p>{
   
   {.Content}}</p>
    <p>计算md5值:{
   
   {md5 .Content}}</p>
</body>
</html>

If we want to use custom functions in templates, we need to register these functions in the FuncMap of the "html/template" package. Normally, we store custom functions and templates in different files, and then load them in during program initialization.

Of course, there is more than one method. Both of the above methods can be used, and you can choose according to your personal preference.

At the same time, I would like to add a supplement to the second scenario and explain another specific implementation used in this scenario.

Suppose we have a file named "funcs.go" in the project, which defines a custom function named "double":

package main

import (
    "html/template"
)

// 自定义函数,将传入的整数翻倍
func double(x int) int {
    return x * 2
}

// 初始化模板,注册自定义函数
var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
    "double": double,
}).ParseFiles("template.html"))

// 渲染模板
func renderTemplate(data interface{}) error {
    err := tmpl.ExecuteTemplate(os.Stdout, "template.html", data)
    if err != nil {
        return err
    }
    return nil
}

In the above code, we register the " double " function into the FuncMap of the " html/template " package , and initialize the template using the " template.Must " function. In the template file " template.html " we can use the " double " function like this :

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>My Template</title>
</head>
<body>
    <p>{
   
   { double . }}</p>
</body>
</html>

In the above template, we use the dot " . " to represent the current data object , and then call the custom function through " double .". When we call the " renderTemplate " function, the data object is passed into the template for rendering and the result is output.

I hope this can help you and give the blogger a like! !

Guess you like

Origin blog.csdn.net/A_LWIEUI_Learn/article/details/131198318