go - 使用 Echo 和 html/template 如何将 HTML 传递给模板?

标签 go go-html-template

我正在使用Echo为了构建我的第一个小型 Go Web 服务,我使用了他们提供的示例,使用 html/template 作为 HTML 页面模板来简化页面管理。

在其中一个页面上,我从后端 API 收集数据并希望将其显示在表格中。我正在生成 HTML,然后将其传递到模板中。不幸的是 html/template 将其编码为安全文本,而不是让 HTML 通过。

我可以在 html/template 文档中看到如何判断 HTML 在那里是安全的,但我不确定如何在 Echo 中做同样的事情。

如何才能使通过 Render 传递的 HTML 被接受为 HTML,而不是编码?

go 文件和模板的简化版本:

server.go

package main

import (
  "io"
  "html/template"

  "github.com/labstack/echo"
  "github.com/labstack/echo/middleware"
  "github.com/labstack/gommon/log"
)

type Template struct {
  templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
    return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
  t := &Template{
    templates: template.Must(template.ParseGlob("views/*.html")),
  }

  e := echo.New()
  e.Logger.SetLevel(log.INFO)
  e.Use(middleware.Logger())

  e.Renderer = t

  e.GET("/", homePage)

  // HTTP server
  e.Logger.Fatal(e.Start(":1323"))
}

pages.go

package main

import (
  "github.com/labstack/echo"
)

func homePage(c echo.Context) error {
  return c.Render(http.StatusOK, "home", "<p>HTML Test</p>")
}

views/home.html

{{define "home"}}
{{template "head"}}
{{template "navbar"}}

{{.}}

{{template "foot"}}
{{end}}

最佳答案

这已涵盖in the html/template package summary :

By default, this package assumes that all pipelines produce a plain text string. It adds escaping pipeline stages necessary to correctly and safely embed that plain text string in the appropriate context.

When a data value is not plain text, you can make sure it is not over-escaped by marking it with its type.

例如:

return c.Render(http.StatusOK, "home", template.HTML("<p>HTML Test</p>"))

关于go - 使用 Echo 和 html/template 如何将 HTML 传递给模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48714438/

相关文章:

go - 如何在golang中使用事务

javascript - 使用来自 WebSocket 的 JSON 的 Golang 模板范围(for 循环)

javascript - 如何在 JavaScript block 的 HTML 模板中禁用转义 URL/字符串

go - 如何在 golang 中使用不同的接口(interface)在单个网页中执行多个模板?

oauth - 如何使用 Google API 交换 OAUTH token ( Go )

postgresql - 通过 Golang SQLX 执行的 postgres 查询中的间隔参数

go - 如何在 atom.io 下运行我的 golang 主包?

go - 从代码执行二进制文件失败但从命令行运行它有效

go - 简单如果不工作 go 模板

go - 如何在{{define“…”}}的gotemplate中为&lt;input&gt;和<label>标签创建唯一的ID?