doulachan8217 2018-02-09 21:35
浏览 63
已采纳

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

I'm using Echo to build my first small Go web service and I went with the example they provide for using html/template for HTML page templates to simplify page management.

On one of the pages I'm collecting data from a backend API and wanted to display it in a table. I'm generating the HTML and then passing it into the template. Unfortunately html/template is encoding it as safe text rather than letting the HTML pass through.

I can see in the html/template docs how you could tell it the HTML is safe there but I'm not sure how to do that same thing inside Echo.

How do I make it so that HTML passed through Render is accepted as HTML instead of encoded?

Simplified versions of the go files and template:

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}}
  • 写回答

1条回答 默认 最新

  • dqsot35145 2018-02-09 22:00
    关注

    This is covered 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.

    For example:

    return c.Render(http.StatusOK, "home", template.HTML("<p>HTML Test</p>"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么