Go html/template 模板函数

Go html/template 模板函数概述

通过自定义模板函数可以实现更复杂的模板逻辑,在开发中是非常常用的。

模板函数实现步骤

1. 定义模板函数;

2. 使用 template.Funcs() 注册模板函数;

3. 在模板中使用函数,语法 :

{{函数名称 参数}}

示例

go 源码

package main

import (
	"html/template"
	"net/http"
)

// 定义模板函数
// 多个参数使用切片或者map 传递
func addition(nums []int) int {
	return nums[0] + nums[1]
}

func subtraction(nums []int) int {
	return nums[0] - nums[1]
}

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 此处注意使用 New() 函数先声明模板
		t := template.New("index.html")
		// 注册模板函数
		t.Funcs(template.FuncMap{
			"addition":    addition,
			"subtraction": subtraction,
		})
		t.ParseFiles("./templates/index.html")
		t.Execute(w, []int{3, 1})
	})
	http.ListenAndServe(":8080", nil)
}

html 源码

<html>
<body>
    <div>
        hi...{{addition .}}...{{subtraction .}}
    </div>
</body>
</html>