go - 使用继承渲染 html/template

go - Render html/template with inheritance

我有两个 html 模板,index.html 扩展 base.html

base.html是这样的:

{{ define "base" }}
<html>
<head>
    <meta charget="utf-8">
    <title>{{ template "title" . }}</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="/js/isotope.pkgd.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/css/style.css">
</head>
<body>
    {{ template "index" . }}
</body>
</html>
{{ end }}

index.html

{{ define "title" }}Homepage{{ end }}
{{ define "index" }}
<div class="wrapper">
    <div class="page-content">
        <div class="container">
            <div class="left">
                <img src="../public/images/img_landing_page_mac.png">
            </div>
            <div class="right">
                <h2 style="font-size: 33px; letter-spacing: 5px">Organize <br>Modern Knowledge<br> for Mankind</h2>
                <p style="font-size: 20px;margin-top: 35px;letter-spacing: 4px">Consume, Colect and Revisit <br>Knowledge at Your Fingertips</p>
                <a href="#" style="margin-top: 80px;display: inline-block;margin-left: -17px"><img src="../public/images/btn_get_chrome.png"></a>
            </div>
        </div>
    </div>
</div>
{{ end }}

在带有回调处理程序的浏览器上请求路径时应该呈现:

func IndexHandler(w http.ResponseWriter,r *http.Request){
    files:=[]string{"base","index"}
    util.RenderTemplate(w,nil,files...)
}

RenderTemplate 是渲染的包装函数

func RenderTemplate(w http.ResponseWriter,data interface{},tmpl... string){
    cwd,_:=os.Getwd()
    files:=make([]string, len(tmpl))
    for i,file:=range tmpl{
        files[i]=filepath.Join(cwd,"./view/"+file+".html")
    }
    t,err:=template.ParseFiles(files...)
    if err!=nil{
        http.Error(w,err.Error(),http.StatusInternalServerError)
        return
    }
    templates:=template.Must(t,err)
    err=templates.Execute(w,data)
    if err!=nil {
        http.Error(w,err.Error(),http.StatusInternalServerError)
    }
}

启动服务器后,我在浏览器上请求该路径,但根本没有呈现任何内容。我错过了什么?这里好像没有理解继承

我遵循本教程,尝试使用继承/扩展呈现模板:

https://elithrar.github.io/article/approximating-html-template-inheritance/

define 动作不执行模板,只有 templateblock 动作执行。很可能您只想从基本模板(第一行和最后一行)中删除 define,它会按预期工作。

或者您可以使用 Template.ExecuteTemplate 函数代替 Template.Execute。它接受模板的名称: 错误 = templates.ExecuteTemplate(w, "base", 数据)

或者如果您使用的是 Go1.6 或更新版本,您可以尝试 block 操作而不是 define

请注意,请考虑使用 gofmt