惜风不起、唯有努力!
html/template简单使用

html/template简单使用

//tmpl示列

package main

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

type Ren struct {
	name string
	Age int
	Addr string
	Height float64
	Weight float64
	Elect_result bool
}

func nameless (w http.ResponseWriter, r *http.Request)  {
	//解析模板
	//s.tmpl是当前路径中的文件,内容是html。
	//z是数据。err接收错误信息
	z,err := template.ParseFiles("./s.tmpl")
	if err != nil {
		fmt.Printf("tmpl error: %v \n",err )
		return
	}

	user := Ren{
		name: "tom",
		Age: 20,
		Addr: "北京",
		Height: 178.5,
		Weight: 143.5,
		Elect_result: true,
	}
	user02 := map[string]interface{}{
		"name": "xiao fei",
		"age": "27",
		"addr": "shang hai",
	}

	qiul := []string{
		"篮球",
		"足球",
		"兵乓球",
	}

	//渲染模板
	//以map嵌套方式传入多个渲染参数
	err = z.Execute(w, map[string]interface{}{
		"user": user,
		"user02": user02,
		"qiul": qiul,
	})
	if err != nil {
		fmt.Printf("z, lr error: %v \n", err)
		return
	}
	fmt.Printf("name: %v \n",user.name)

}

func main ()  {
	//执行路由函数
	http.HandleFunc("/", nameless)
	err := http.ListenAndServe(":3000",nil)
	if err != nil {
		fmt.Printf("http start fail,error: %v", err)
		return
	}
}

s.tmpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>go</title>
</head>

<body>

    <div>
        <h2>自我介绍</h2>
        <hr \>
        <p>我叫{{.user02.name}},今年{{ .user02.age }}岁,来自{{ .user02.addr }}</p>
        <p>我的身高和体重分别是{{ .user.Height }},{{ .user.Weight }},结果为{{ .user.Elect_result }}</p>
        <hr \>
    </div>

    <hr \>
    <div>
        <h2>if</h2>
        {{ $num := 20 }}
        {{ $age := .user.Age }}
        {{ if gt $num 20 }}
            <p> >20 </p>
        {{ else }}
            <p> test </p>
        {{ end }}

        {{if gt $age 20}}
            <p>$age</p>
        {{else}}
            <p>test</p>
        {{end}}
    </div>

    <hr \>
    <h2>for</h2>
    <div>
        {{range $i,$v := .qiul}}
            <p>{{$i}} *** {{$v}}</p>
        {{else}}
            空值
        {{end}}
    </div>

</body>
</html>

//tmpl自定义函数示列

package main

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

func nameless (w http.ResponseWriter, r *http.Request)  {

	//自定义tmpl使用函数
	f := func(v string)(string,error){
		return v+"--xx", nil
	}
        //New对象和之前方式效果一样
	z := template.New("s.tmpl")
	//注册自定义函数
	z.Funcs(template.FuncMap{
		"fs": f,
	})
	_,err := z.ParseFiles("./s.tmpl")
	if err != nil {
		fmt.Printf("tmpl error: %v \n",err )
		return
	}

	err = z.Execute(w, "alixls")
	if err != nil {
		fmt.Printf("z, lr error: %v \n", err)
		return
	}
}

func main ()  {
	http.HandleFunc("/", nameless)
	err := http.ListenAndServe(":3000",nil)
	if err != nil {
		fmt.Printf("http start fail,error: %v", err)
		return
	}
}

x.tmpl

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>go</title>
</head>

<body>

    <div>
        <p>{{fs .}}</p>
    </div>

</body>
</html>

发表回复

您的电子邮箱地址不会被公开。