【问题标题】:Why don't HTML templates that I have parsed work?为什么我解析的 HTML 模板不起作用?
【发布时间】:2020-11-23 15:14:04
【问题描述】:

我解析了我的模板文件以使我更容易工作。

我将它们命名为{{define "pagearea"}}。 例如{{define "footer"}}。

文件夹布局

  • footer.tmpl - 页脚区域
  • index.tmpl - 我的主页
  • ma​​in.go - 去代码:)
  • topheader.tmpl - 顶部 html 的一部分

main.go

package main

import (
    "log"
    "os"
    "html/template"
)

type Home struct {
    Sitelang string
    Sitetitle string
    Sitename         string
    Siteslogan string
}

func main() {
    homeTmpl, err := template.ParseFiles("./topheader.tmpl", "./footer.tmpl",  "./index.tmpl")
    if err != nil {
        log.Fatal("Home page parsing error:", err)
    }

    data := Home{Sitelang: "en",
        Sitetitle: "Home - Render Test",
        Sitename        : "test 1",
        Siteslogan: "mmmmeeeeeuaawww!"}
        homeTmpl.Execute(os.Stdout, data)

}

footer.tmpl:

{{define "footer"}}
<footer>

    <small>
        This is footer area. Test.</small>
</footer>
</body>
</html>
{{end}}

index.tmpl:

{{template "topheader"}}

<h1>
        Main area</h1>

{{template "footer"}}

topheader.tmpl:

{{define "topheader"}}
<!DOCTYPE html>
<html lang="
        {{.Sitelang}}">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>
        {{.Sitetitle}}</title>

</head>

<body>
<header>
    <h1>
            {{.Sitename}}
    </h1>
    <p>
            {{.Siteslogan}}
    </p>
</header>


{{end}}

构建命令:go build .

我真的不知道我错过了什么。这里有什么问题?

【问题讨论】:

    标签: go go-templates go-html-template


    【解决方案1】:

    您使用template.ParseFiles() 来解析模板文件。这将解析所有文件,并返回一个模板,该模板将“包含”所有已解析的模板作为关联模板。返回的 template.Template 将代表 first 模板。引用template.ParseFiles():

    返回的模板名称将包含第一个文件的(基本)名称和(解析的)内容。

    然后您使用Template.Execute() 执行您正在调用其方法的模板。因此,在您的情况下,这将是 topheader.tmpl,但该模板不会生成任何输出,该模板只是定义一个模板:{{define "topheader"}}。

    您很可能想要执行index.tmpl,因此请使用Template.ExecuteTemplate(),您可以在其中通过名称识别可执行模板(并且不要忘记检查返回的错误):

    err = homeTmpl.ExecuteTemplate(os.Stdout, "index.tmpl", data)
    if err != nil {
        log.Fatal("index template execution failed:", err)
    }
    

    另一个错误是,当您的 index.html 模板使用 {{template}} 操作包含(执行)其他模板时,您没有向它们传递任何参数,但您想使用初始参数。

    所以在调用其他模板时传递当前参数。你的index.html 应该是:

    {{template "topheader" .}}
    
    <h1>
            Main area</h1>
    
    {{template "footer" .}}
    

    查看相关问题:

    Go template name

    Golang template engine pipelines

    【讨论】:

    • 它不会在模板中放置变量。例如&lt;p&gt; &lt;/p&gt; 真:&lt;p&gt;mmmmeeeeeuaawww!&lt;/p&gt;
    • @SeanTolstoyevski 也修复了该问题,请参阅编辑后的答案。
    • 现在一切都很好。我是新来的。我需要删除我的 cmets。
    • @SeanTolstoyevski 这取决于你。如果他们现在没有用,你可以。如果帖子回答了您的问题,请考虑支持并接受它。
    猜你喜欢
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    相关资源
    最近更新 更多