【问题标题】:With Echo and html/template how can I pass HTML to the template?使用 Echo 和 html/template 如何将 HTML 传递给模板?
【发布时间】:2018-02-10 06:00:24
【问题描述】:

我正在使用 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}}

【问题讨论】:

    标签: go go-html-template


    【解决方案1】:

    这是覆盖in the html/template package summary

    默认情况下,此包假定所有管道都生成纯文本字符串。它添加了必要的转义管道阶段,以便在适当的上下文中正确、安全地嵌入纯文本字符串。

    当一个数据值不是纯文本时,你可以通过标记它的类型来确保它没有被过度转义。

    例如:

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

    【讨论】:

    • 是的,我在顶部看到了关于转义的部分。我不确定“标记”部分是如何工作的。使用template.HTML("str")如何返回“标记”字符串?
    • 如果你看definition for template. HTML,它只是一个基于string的类型。通过将字符串强制为该类型,您是在告诉包它不需要转义它。
    • 拉德。谢谢。仍在学习 go 和来自主要是鸭子类型的语言,我想我误解了 Types 在这个意义上是如何工作的。这很酷。
    猜你喜欢
    • 2017-06-20
    • 1970-01-01
    • 2011-03-13
    • 2016-06-16
    • 1970-01-01
    • 2017-12-29
    相关资源
    最近更新 更多