随笔 - 91,  文章 - 0,  评论 - 3,  阅读 - 47581

嵌套模板

模板可以嵌套使用其他的模板,这个嵌套的模板可以是单独的文件,也可以是用define来定义的。
用define定义的模板语法:

{{ define "文件名"}}
内容

<!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>
<!--用define定义的模板-->
    {{template "ol.tmpl"}}
    <p>{{.Name}}</p>
</body>
</html>
{{ define "ol.tmpl"}}
<ol>
    <li>问题1</li>
    <li>问题2</li>
    <li>问题3</li>
</ol>
{{end}}

ul.tmpl文件内容如下:

<ul>
    <li>测试1</li>
    <li>测试2</li>
    <li>测试3</li>
</ul>
package main

import (
	"fmt"
	"net/http"
	"text/template"
)
type User struct {
	Name   string //首字母大写,是对外暴露的,才能被调用,小写是不能被调用的
	Gender string //
	Age    int
}
func nestTemplate(w http.ResponseWriter, r *http.Request) {
	//解析模板 必须子模版在后面
	tmpl, err := template.ParseFiles("./t.tmpl", "./ul.tmpl")
	if err != nil {
		fmt.Println("create template failed, err:", err)
		return
	}
	user := User{
		Name:   "小王子",
		Gender: "男",
		Age:    18,
	}
//执行模板
	tmpl.Execute(w, user)
}
func main() {
        //注册路由处理函数
	http.HandleFunc("/hello", nestTemplate)
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}

结果:

posted on   飞飞乐园  阅读(77)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示