golang 模板继承

2020-05-07  本文已影响0人  韩小禹
package main

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

func index(w http.ResponseWriter, r *http.Request) {
    // 定义模板
    // 解析模板
    // 父模板和子模板的顺序不能乱,父在前,子在后
    t, err := template.ParseFiles("./layouts/main.tmpl","./layouts/content.tmpl")
    if err != nil{
        fmt.Printf("parse files failed, err : %v\n", err)
        return
    }
    // 渲染模板
    // 渲染模板时使用ExecuteTemplate函数,需要制定要被渲染的模板名称
    t.ExecuteTemplate(w, "content.tmpl","index")
}


func main() {
    http.HandleFunc("/index", index)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Printf("http server failed, err : %v\n", err)
        return
    }
}

<html>
<head>
    <title>模板继承</title>
    <style>
        *{
            margin :0;
        }
        .nav{
            height: 50px;
            position:fixed;
            width: 100%;
            top:0;
            background-color: burlywood;
        }
        .main{
            margin-top: 50px;
        }
        .menu{
            width: 200px;
            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">
        <!--定义一个区块-->
        {{block "content" .}}{{end}}
    </div>
</div>
</body>
</html>
{{template "main.tmpl" .}}
{{define "content"}}
<h1>
    这里是子模板,{{ . }}
</h1>
{{end}}
上一篇 下一篇

猜你喜欢

热点阅读