go模板继承

当好几个页面的样式都一样,但是内容不一样的话,只需要定义一个根模板,然后让其他模板继承这个根模板,然后自己定义内容即可

根模板

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>模板继承</title>
    <style>
        * {
            margin: 0;
        }
        .nav {
            height: 50px;
            width: 100%;
            position: fixed;
            top: 0;
            background-color: burlywood;
        }
        .main {
            margin-top: 50px;
        }
        .menu {
            width: 20%;
            height: 100%;
            position: fixed;
            left: 0;
            background-color: cornflowerblue;
        }
        .center {
            text-align: center;
        }
    </style>
</head>

<body>

<div class="nav"></div>
<div class="main">
    <div class="menu"></div>
    <div class="content center">
    <!--        这里用来让其他模板继承,模板名称叫content,也会传过去个参数. -->
        {{block "content" .}}{{end}}
    </div>
</div>

</body>
</html>

子模版1

<!--继承根模板-->
{{template "base.tmpl" .}}
<!--重新定义块模板-->
{{define "content"}}
    <h1>这是home2页面</h1>
    <p>hello,{{ . }}</p>
{{end}}

子模版2

<!--继承根模板-->
{{template "base.tmpl" .}}
<!--重新定义块模板-->
{{define "content"}}
    <h1>这是index2页面</h1>
    <p>hello,{{ . }}</p>
{{end}}

解析模板

func index2(w http.ResponseWriter,r *http.Request) {
//顺序不能错,先根模板,再子模版
	t,err := template.ParseFiles("./templates/base.tmpl","./templates/index2.tmpl")
	if err != nil {
		fmt.Printf("parse template failed, err %v\n", err)
		return
	}

	name := "小王子"
	t.ExecuteTemplate(w,"index2.tmpl",name)
}
func home2(w http.ResponseWriter,r *http.Request) {
	t,err := template.ParseFiles("./templates/base.tmpl","./templates/home2.tmpl")
	if err != nil {
		fmt.Printf("parse template failed, err %v\n", err)
		return
	}

	name := "小王子"
	t.ExecuteTemplate(w,"home2.tmpl",name)
}

main函数

func main() {
	http.HandleFunc("/index2",index2)
	http.HandleFunc("/home2",home2)

	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("HTTP server start failed,err : %v", err)
		return
	}
}

结果

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值