去模板扩展和超级?

时间:2014-09-24 01:11:54

标签: templates go flask

在Flask中,我们可以从模板中的base.html扩展。如何使用Go的标准模板库扩展或super()?否则,如果我需要使用顶栏,我将不得不手动复制并粘贴顶栏的代码。请告诉我。

5 个答案:

答案 0 :(得分:1)

它的主旨是你会有一些作为初始模板执行的父模板(我们称之为布局),并且在该布局中父模板就像{{template" someName& #34; }}

请参阅:https://github.com/jadekler/git-go-websiteskeleton/blob/master/templates/layout.html#L40。那个repo是一个非常轻量级的骨架,带有基本的go包 - 你可能会发现它有一些价值。

答案 1 :(得分:1)

我用模板遇到了这个问题。在支持继承之前,我已经使用了各种模板引擎。

为了解决这个限制,我实际上已经复制了标准文本/模板包以删除重定义错误(来自template.go)和test(来自multi_test.go)。这允许您在模板中重新定义模板/定义块。

我创建了一个包含示例等的github repo https://github.com/d2g/goti。我还需要在repo上做很多事情(标签版本等)[提示请求欢迎提示]。

答案 2 :(得分:0)

在Go中,您可以使用html/template

然后你可以定义标题,正文和页脚看起来像

// header.tpl:
{{define "header"}}
<html>
<head></head>
{{end}}

// body.tpl:
{{template "header" .}}
{{define "body"}}
<body>
</body>
{{end}}
{{template "footer" .}}

// footer.tpl:
{{define "footer"}}
</html>
{{end}}

s1, _ := template.ParseFiles("header.tpl", "body.tpl", "footer.tpl") //create a set of templates from many files.
s1.Execute(os.Stdout, nil)

参考:http://golangtutorials.blogspot.com/2011/11/go-templates-part-3-template-sets.html

答案 3 :(得分:0)

如果您正在为Go搜索类似jinja2 / Django的模板语言(它支持前面提到的模板继承模板包含),您应该尝试pongo2

答案 4 :(得分:0)

我找到的一个解决方案是将所有内容引用到我的base.gohtml,然后使用逻辑来确定应包含哪些模板。

func dashboard(w http.ResponseWriter, req *http.Request) {
    data := struct {
        Page string
    }{
        "dashboard",
    }
    err := tpl.ExecuteTemplate(w, "base", data)
    if err != nil {
        log.Fatalln(err)
    }
}

然后在我的基本模板中:

headers, navs, css
{{if eq .Page "dashboard"}}
    {{template "dashboard"}}
{{else if .Page "login"}}
    {{template "login"}}
{{else}}
    ...
{{end}}
footers, scripts