【问题标题】:html template returns text instead of htmlhtml 模板返回文本而不是 html
【发布时间】:2021-10-21 08:51:11
【问题描述】:

我有以下代码:

package main

import (
    "fmt"
    htmlTempl "html/template"
    "log"
    "net/http"
)

var templatesHtml *htmlTempl.Template
var err error

func init() {
    fmt.Println("Starting up.")
    templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}

func test(w http.ResponseWriter, r *http.Request) {
    err = templatesHtml.ExecuteTemplate(w, "other.html", nil)
    if err != nil {
        log.Fatalln(err)
    }
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
    http.HandleFunc("/test", test)
    server.ListenAndServe()
}

我的模板是:

// Content of base.html:
{{define "base"}}
<html>
  <head>{{template "head" .}}</head>
  <body>{{template "body" .}}</body>
</html>
{{end}}

// Content of other.html:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}

我在http://127.0.0.1:8080/test 得到的输出是:

虽然我期待显示正常的 HTML 页面!

【问题讨论】:

  • // 不是模板文件中的注释标记,正如您所想的那样。查看文档以了解如何在模板中编写 cmets。或者只是删除评论,它并没有真正增加任何价值,是吗?另一种选择,如果你必须在文件中保留 // 东西,将 other.html 文件的 html 内容包装在它自己的 define 操作中,就像你对 base.html 所做的那样,只要确保你通过ExecuteTemplate 方法生成的模板的正确名称。
  • @mkopriva 谢谢,它通过删除/&lt;!-- --&gt; 评论它们起作用,使用define 给出错误panic: template: other.html:5: unexpected &lt;define&gt; in command
  • 我假设你把它放错了地方,或者使用了错误的语法,没有理由第三个有效的define(注意你在那个文件中已经有两个)应该突然开始失败。模板文件可以有多少个定义并没有限制。没有看到更新的文件,但我可以提供更多帮助。

标签: go


【解决方案1】:

感谢mkoprivs提供的cmets,错误在于使用//作为评论标记,已通过将它们替换为html内容评论标记来解决,如下所示:

<!-- Content of other.html: -->
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}

现在一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多