Golang从文件中嵌入HTML [英] Golang embed html from file

查看:73
本文介绍了Golang从文件中嵌入HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的HTML文件,该如何在Golang中进行操作:

How can I do in Golang if I have an HTML file like this:

<html>
  <head lang="en">

  </head>
  <body>
    <header>{{.Header}}</header>
    <div class="panel panel-default">

    </div>
  </body>
</html>

我想将一部分代码嵌入到其他文件的标头标签中,如下所示:

and I want to embed a part of code into to header tags from an other file like this:

<div id="logo"></div><div id="motto"></div>

我的尝试:

header, _ := template.ParseFiles("header.html")
c := Content{Header: ""}
header.Execute(c.Header, nil)

index := template.Must(template.ParseFiles("index.html"))
index.Execute(w, c)

推荐答案

如果使用">code> template.ParseGlob() ,这些模板可以互相引用,也可以互相包含.

If you parse all your template files with template.ParseFiles() or with template.ParseGlob(), the templates can refer to each other, they can include each other.

将您的 index.html 更改为包含 header.html ,如下所示:

Change your index.html to include the header.html like this:

<html>
  <head lang="en">

  </head>
  <body>
    <header>{{template "header.html"}}</header>
    <div class="panel panel-default">

    </div>
  </body>
</html>

然后是完整的程序(从当前目录解析文件,执行"index.html" 并将结果写入标准输出):

And then the complete program (which parses files from the current directory, executes "index.html" and writes the result to the standard output):

t, err := template.ParseFiles("index.html", "header.html")
if err != nil {
    panic(err)
}

err = t.ExecuteTemplate(os.Stdout, "index.html", nil)
if err != nil {
    panic(err)
}

使用 template.ParseGlob()可能看起来像这样:

With template.ParseGlob() it could look like this:

t, err := template.ParseGlob("*.html")
// ...and the rest is the same...

输出(打印在控制台上):

The output (printed on the console):

<html>
  <head lang="en">

  </head>
  <body>
    <header><div id="logo"></div><div id="motto"></div></header>
    <div class="panel panel-default">

    </div>
  </body>
</html>

这篇关于Golang从文件中嵌入HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆