{Go} How to use template composition ?

Basic Gramma

define action
{{define "templ_name"}} some html & fields {end}}

do not allow nested "define"

template action
{{template "templ_name" }}
{{template "templ_name" pipeline}}
block action
{{block "name" pipeline}} some html & fields {{end}}

How to organize template files?

see a example

-- head.tpl

{{define "header"}}
<head>
    <title>You're in a {{.Where}}</title>
</head>
{{end}}

-- foot.tpl

{{define "footer"}}
<div>nice guest</div>
{{end}}

-- panda.tpl

{{define "layout"}}
<!DOCTYPE html>
<html>
{{template "header" .Head}}
<body>
    {{block "panda" .Panda}}
    <div>
        <p>I'm {{.Name}}</p>
        <p>Weight: {{.Weight}}</p>
        <p>Age:{{.Age}}</p>
    </div>
    {{end}}

    {{template "footer"}}
</body>
</html>
{{end}}    

-- panda.go

type Panda struct {
    Name   string
    Weight float32
    Age    int
}

type Head struct {
    Where string
}

type Layout struct {
    Head  Head
    Panda Panda
}

func panda(w http.ResponseWriter, req *http.Request) {
    t, err := template.ParseFiles("tpl/panda.tpl", "tpl/head.tpl", "tpl/foot.tpl")
    if err != nil {
        fmt.Fprintf(w, err.Error())
    }

    head := Head{Where: "zoo"}
    panda := Panda{"Nini", 12.2, 3}
    layout := Layout{head, panda}

    err = t.ExecuteTemplate(w, "layout", layout)

    if err != nil {
        fmt.Fprintf(w, err.Error())
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容