惜风不起、唯有努力!
html/template模板嵌套使用

html/template模板嵌套使用

package main

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

func tmplQt (w http.ResponseWriter, r *http.Request){
        //注意tmpl前后顺序
	f,err := template.ParseFiles("./qt01.tmpl","qt02.tmpl")
	if err != nil{
		fmt.Printf("tmpls func tmpl error: %v\n",err)
	}

	err = f.Execute(w,"tmplQt test")
	if err != nil{
		fmt.Printf("Execute error: %v\n", err)
	}
}

func main ()  {
	http.HandleFunc("/tmpl/qt", tmplQt )
	fmt.Println("start service ......^_^")
	err := http.ListenAndServe(":3000",nil)
	if err != nil {
		fmt.Printf("http start fail,error: %v", err)
		return
	}
}

qt01.tmpl

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

<body>
    <h2>模板嵌套</h2>
    {{template "qt02.tmpl"}}
    <hr \>
    {{template "qt03.tmpl"}}

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

</body>
</html>
{{define "qt03.tmpl"}}
    <a>1</a>
    <a>2</a>
    <li>333</li>
{{end}}

qt02.tmpl

<h4>my is qt02</h4>

发表回复

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