dongqiuqiu4736 2018-08-16 23:23
浏览 200
已采纳

Golang tmpl HTML文本被解释为纯文本,而不是使用HTML

I have some data given to my template using Go that contains html tags. When I try to display this data, it displays the full text literally, including the HTML tags. Here's the code:

In my .tmpl, I am looping through an object called .SimRpms whose {{ $value }} has html in it like <br>:

{{ range $key, $value := .SimRpms }}
    <div class="col-md-4">
        <div class="panel panel-default">
          <div class="panel-heading">{{ $key }}</div>
          <div class="panel-body">{{ $value }}</div>
        </div>
    </div>
{{ end }}

However when I look at the rendered page, the {{ $value }} is rendered as plain text instead of html:

html is rendered as plain text

How can I get {{ $value }} to interpret the text as HTML?

Here's what it looks like in the JS Console:

js console

I know this is similar to this question: Golang html output is being interpreted as plain text instead of being received as html however the rest of the page is displaying HTML ok and the content type of the entire page has been set already, but this little panel isn't displaying the HTML (it's displaying it literally).

  • 写回答

2条回答 默认 最新

  • dongpochi9741 2018-08-17 05:18
    关注
    package main
    
    import (
        "html/template"
        "log"
        "net/http"
    )
    
    func main() {
        http.HandleFunc("/", SayHello)
        log.Fatal(http.ListenAndServe(":2332", nil))
    }
    func SayHello(w http.ResponseWriter, r *http.Request) {
        t, err := template.ParseGlob("hello.gtml")
        if err != nil {
            panic(err)
        }
        t.Execute(w, map[string]template.HTML{"name": template.HTML("<a>Katie Sissons</a>")})
        return
    }
    

    works with the template

    hello.gtml below.

    <html>
        <head></head>
        <body>{{ .name  }}</body>
    </html>
    

    html/template package treats template.HTML as a type and applies escape to normal strings. If you want your string to go without escape, this type can do that for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上