{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())
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容