猿问

Go中的HTML模板-插入html作为pipleline的值

我正在使用Go模板输出html,并通过管道插入一些值。事情是原始HTML值之一,我不想对其进行转义。但是当执行模板时,将对其进行转义。


这是代码


package main 


import (

    "fmt"

    "io/ioutil"

    "log"

    "net/http"

    "html/template"

    "encoding/xml"

)


type RSS struct {

    XMLName xml.Name `xml:"rss"`

    Items Items `xml:"channel"`

}

type Items struct {

    XMLName xml.Name `xml:"channel"`

    ItemList []Item `xml:"item"`

}

type Item struct {

    Title string `xml:"title"`

    Link string `xml:"link"`

    Description string `xml:"description"`

}


func main() {

    res, err := http.Get("http://news.google.com/news?hl=en&gl=us&q=samsung&um=1&ie=UTF-8&output=rss")

    if err != nil {

        log.Fatal(err)

    }

    asText, err := ioutil.ReadAll(res.Body)

    if err != nil {

        log.Fatal(err)

    }


    var i RSS

    err = xml.Unmarshal([]byte(asText), &i)

    if err != nil {

        log.Fatal(err)  

    }


    res.Body.Close()


    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

              handler(w, r, i)

       })

    http.ListenAndServe(":8080", nil)

}


func handler(w http.ResponseWriter, r *http.Request, i RSS) {

    t, _ := template.ParseFiles("index.html")

    t.Execute(w, i.Items)

}

这是HTML:


<html>

    <head>

    </head>


    <body>

        {{range .ItemList}}

        <div class="news-item">

            <p>

                <a href="{{.Link}}">{{.Title}}</a>

            </p>

            <p>{{.Description}}</p>

        </div>

        {{end}}

    </body>

</html>

输出看起来像这样:


<div class="news-item">

            <p>

                <a href="http://news.google.com/news/url?sa=t&amp;fd=R&amp;usg=AFQjCNFd-5CF7Rwy7sjNZ2-fSOLkO6ri5g&amp;url=http://www.pehub.com/186539/what-apple-might-learn-samsung/">What Apple Might Learn from Samsung - Private Equity Hub (press release)</a>

            </p>

        </div>

说明是转义的html,我希望它是常规的html


跃然一笑
浏览 242回答 2
2回答

陪伴而非守候

将管道的描述字段的类型template.HTML改为string,而不是,如下所示:type pipeObject struct {&nbsp; &nbsp; Description template.HTML}&nbsp;pipe := &pipeObject{&nbsp; &nbsp; template.HTML("<p>Your safe HTML</p>"),}相关文档:template.HTML

PIPIONE

将管道的描述字段的类型template.HTML改为string,而不是,如下所示:type pipeObject struct {&nbsp; &nbsp; Description template.HTML}&nbsp;pipe := &pipeObject{&nbsp; &nbsp; template.HTML("<p>Your safe HTML</p>"),}相关文档:template.HTML
随时随地看视频慕课网APP

相关分类

Go
我要回答