小编典典

GoLang中的HTML部分

go

我刚开始使用Go,我想用它创建一个Web应用程序。我现在要尝试的是以handlebarsjs风格使用模板。我想将页眉和页脚从主页中拉出来,以便可以将它们插入每个网页中。

我当前的设置应该解析主页,页眉和页脚HTML文件并缓存它们。然后,我执行home.html模板,该模板具有用于页面Title,header.html文件和footer.html文件的字段。

每当我搜索相似的页面时,我只会看到javascript页面,因此,如果这是转贴,请告诉我在哪里查找。

编辑:
我已经更新了我的代码,以从@Minty和@putu的答案中获取提示。我正在尝试读取html文件并将其存储在数据映射中,同时还将模板添加define到我的模板中。我正在处理一些新的错误,因此该网站目前无法渲染。但是,如果您可以提供任何新的提示,那将会很有帮助。

server.go

package main

import (
    "html/template"
    "io/ioutil"
    "net/http"
    "regexp"
)

var tPath = "./temps/"
var dPath = "./data/"

var templates = template.Must(template.ParseFiles(tPath+"home.html", dPath+"header.html", dPath+"footer.html"))
var validPath = regexp.MustCompile("^/")

func rootHandler(wr http.ResponseWriter, req *http.Request) {
    title := "home"
    headerFile, headErr := ioutil.ReadFile(dPath + "header.html")
    footerFile, footErr := ioutil.ReadFile(dPath + "footer.html")

    if headErr != nil || footErr != nil {
        http.Error(wr, headErr.Error(), http.StatusInternalServerError)
        http.Error(wr, footErr.Error(), http.StatusInternalServerError)
    }

    data := map[string]interface{}{
        "Title":  title,
        "Header": string(headerFile),
        "Footer": string(footerFile),
    }

    err := templates.ExecuteTemplate(wr, title+".html", data)

    if err != nil {
        http.Error(wr, err.Error(), http.StatusInternalServerError)
    }
}

func main() {
    http.HandleFunc("/", rootHandler)
    http.ListenAndServe(":8080", nil)
}

home.html:

{{define "homeHTML"}}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>{{.Title}} - MySite</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        {{.Header}}
        <h1>Welcome!</h1>
        {{.Footer}}
    </body>
</html>
{{end}}

Header.html:

{{define "headerHTML"}}
<header>
    <h1>MySite</h1>
    <br>
    <nav>
        <a href="/">Home</a>
    </nav>
</header>
{{end}}

Footer.html

{{define "footerHTML"}}
<footer>
    <p>Thank You for Visiting</p>
</footer>
{{end}}

阅读 261

收藏
2020-07-02

共1个答案

小编典典

这是完整的工作示例。

// home.html inside temps folder
{{define "homeHTML"}}

{{template "headHTML" .}}

{{template "headerHTML" .}}

{{template "footerHTML" .}}

{{end}}

// head.html inside data folder
{{define "headHTML"}}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>{{.title}} - MySite</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>  
{{end}}

// header.html inside data folder
{{define "headerHTML"}}
<header>
    {{.header}}
    <h1>Welcome to my site!</h1>
    <br>
    <nav>
        <a href="/">Home</a>
    </nav>
</header>
{{end}}


// footer.html inside data folder
{{define "footerHTML"}}
<h1>Welcome! {{.footer}}</h1>
<footer>
<p>Thank You for Visiting</p>
</footer>
</body>
</html>
{{end}}

和代码将是这样的

package main

import (
    "html/template"
    "io/ioutil"
    "net/http"
    "path/filepath"
    "strings"
)

var tPath = "./temps/"
var dPath = "./data/"

var templateDirs = []string{"temps", "data"}
var templates *template.Template

func getTemplates() (templates *template.Template, err error) {
    var allFiles []string
    for _, dir := range templateDirs {
        files2, _ := ioutil.ReadDir(dir)
        for _, file := range files2 {
            filename := file.Name()
            if strings.HasSuffix(filename, ".html") {
                filePath := filepath.Join(dir, filename)
                allFiles = append(allFiles, filePath)
            }
        }
    }

    templates, err = template.New("").ParseFiles(allFiles...)
    return
}

func init() {
    templates, _ = getTemplates()
}

func rootHandler(wr http.ResponseWriter, req *http.Request) {
    title := "home"

    data := map[string]interface{}{
        "title":  title,
        "header": "My Header",
        "footer": "My Footer",
    }

    err := templates.ExecuteTemplate(wr, "homeHTML", data)

    if err != nil {
        http.Error(wr, err.Error(), http.StatusInternalServerError)
    }
}

func main() {
    http.HandleFunc("/", rootHandler)
    http.ListenAndServe(":8080", nil)
}
2020-07-02