在Golang的“html / template”包中遇到HTML()函数问题

时间:2013-12-27 21:58:13

标签: html templates go

我遇到了使"html/template"包正确解析模板的问题。我正在尝试将HTML内容解析为我所创建的模板页面,但是,当我尝试时,解析后的页面最终会使用转义的HTML而不是我想要的实际代码。

The Go documentation说我可以简单地使用HTML()函数将字符串转换为type HTML,这已知是安全的,应该以HTML格式解析。我在Contenttype Page中创建了template.HTML字段,编译得很好,但是当我在第53行使用template.HTML(content)函数时,我收到编译错误说:

template.HTML undefined (type *"html/template".Template has no field or method HTML)

使用HTML(content)(不包含前面的template.)会导致此错误:

undefined: HTML

我的最终目标是将其他HTML文件解析为index.html,并由浏览器解释为HTML。

感谢任何帮助。

package main

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

func staticServe() {
    http.Handle(
        "/assets/",
        http.StripPrefix(
            "/assets/",
            http.FileServer(http.Dir("assets")),
        ),
    )
}

var validPath = regexp.MustCompile("^/(|maps|documents|residents|about|source)?/$")


//  This shit is messy. Clean it up.

func servePage(res http.ResponseWriter, req *http.Request) {
    type Page struct {
        Title   string
        Content template.HTML
    }

    pathCheck := validPath.FindStringSubmatch(req.URL.Path)
    path := pathCheck[1]
    fmt.Println(path)

    if path == "" {
        path = "home"
    }

    template, err := template.ParseFiles("index.html")
    if err != nil {
        fmt.Println(err)
    }

    contentByte, err := ioutil.ReadFile(path + ".html")
    if err != nil {
        fmt.Println(err)
    }
    content := string(contentByte)

    page := Page{strings.Title(path) + " - Tucker Hills Estates", template.HTML(content)}

    template.Execute(res, page)
}

//  Seriously. Goddamn.

func serveSource(res http.ResponseWriter, req *http.Request) {
    sourceByte, err := ioutil.ReadFile("server.go")
    if err != nil {
        fmt.Println(err)
    }
    source := string(sourceByte)
    io.WriteString(res, source)
}

func main() {
    go staticServe()
    http.HandleFunc("/", servePage)
    http.HandleFunc("/source/", serveSource)
    http.ListenAndServe(":9000", nil)
}

2 个答案:

答案 0 :(得分:8)

之前导入了“html / template”,这一行

template, err := template.ParseFiles("index.html")

隐藏模板包,因此当您稍后执行template.HTML时,您正在寻找模板对象上的HTML属性,而不是包中名为HTML的内容。< / p>

要防止这种情况,请更改变量的名称。

tmpl, err := template.ParseFiles("index.html")

答案 1 :(得分:0)

您正在使用名为template的变量为您的包着色。最简单的修复方法可能是将变量名称更改为tmpl或其他内容。