自定义函数和模板嵌套

自定义函数和模板嵌套

一、自定义函数

Go的模板支持自定义函数。

package main

import (
	"fmt"
	"net/http"
	"text/template"
)

type UserInfo struct {
	Name   string
	Age    int
	Gender string
}

// 传入单对象
func customFunc(w http.ResponseWriter, r *http.Request) {

	// 1. 编写模板

	// 2. 读取模板 解析指定文件生成模板对象

	// 自定义一个夸人的模板函数,要么返回两个值,第二个返回值必须是error类型
	kua := func(arg string) (string, error) {
		return arg + "-自定义函数", nil
	}
	 // 创建一个名字是customFunctionTemplate.tmpl模板对象,名字一定要与模板的名字对应上
	t, err := template.New("customFunctionTemplate.tmpl").Funcs(template.FuncMap{"kua": kua}).ParseFiles("./customFunctionTemplate.tmpl")
	if err != nil {
		fmt.Printf("read template faild err: %#v", err)
	}

	// 3. 渲染模板
	// 利用给定数据渲染模板,并将结果写入w
	userInfo := UserInfo{
		"RandySun",
		18,
		"男",
	}
	t.Execute(w, userInfo)
}


func main() {

	http.HandleFunc("/customFunc", customFunc)

	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		fmt.Printf("http server run failed err:%#v", err)
	}
}

我们可以在模板文件customFunctionTemplate.tmpl中按照如下方式使用我们自定义的kua函数了。

{{kua .Name}}
<!DOCTYPE html>
<html lang="zh-CN">
<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>Hello Template</title>
</head>
{{kua .Name}}
</html>

二、模板嵌套

嵌套template

我们可以在template中嵌套其他的template。这个template可以是单独的文件,也可以是通过define定义的template。

举个例子: t.tmpl文件内容如下:

<!DOCTYPE html>
<html lang="zh-CN">
<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>tmpl test</title>
</head>
<body>

<h1>测试嵌套template语法</h1>
<hr>
{{/*嵌套另外一个单独的模板文件*/}}
{{template "ul.tmpl"}}
<hr>
{{/*嵌套另外一个defind定义的模板文件*/}}
{{template "ol.tmpl"}}
<p>您好! {{ .Name}}</p>
</body>
</html>

{{ define "ol.tmpl"}}
    <ol>
        <li>吃饭</li>
        <li>睡觉</li>
        <li>打豆豆</li>
    </ol>
{{end}}

ul.tmpl文件内容如下:

<ul>
    <li>注释</li>
    <li>日志</li>
    <li>测试</li>
</ul>

tmplDemo函数的具体内容如下:

package main

import (
	"fmt"
	"net/http"
	"text/template"
)

type UserInfo struct {
	Name   string
	Age    int
	Gender string
}


// 传入单对象
func nestingTmpl(w http.ResponseWriter, r *http.Request) {

	// 解析模板
	// 要将被包含的模板写在后面
	tmpl, err := template.ParseFiles("./nestingTemplate.tmpl", "./ul.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	user := UserInfo{
		Name:   "RandySun",
		Gender: "男",
		Age:    18,
	}
	// 渲染模板
	tmpl.Execute(w, user)
}
func main() {

	http.HandleFunc("/nestingTmpl", nestingTmpl)

	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		fmt.Printf("http server run failed err:%#v", err)
	}
}

注意:在解析模板时,被嵌套的模板一定要在后面解析,例如上面的示例中nestingTemplate.tmpl模板中嵌套了ul.tmpl,所以ul.tmpl要在nestingTemplate.tmpl后进行解析。

image-20211110232449357

在当下的阶段,必将由程序员来主导,甚至比以往更甚。
原文地址:https://www.cnblogs.com/randysun/p/15622032.html