dongyi2534 2016-08-06 12:26
浏览 730
已采纳

如何在Golang模板中打印换行? [重复]

This question already has an answer here:

I have stored some content in MySQL that looks like this.

"Hi!
How are you?
Here is the link you wanted:
http://www.google.com"

When I print it in Golang template, its not parsing correctly. I mean everything displayed in one line.

Its supposed to print like this

Hi!
How are you?
Here is the link you wanted:
http://www.google.com

Here is my template code.

<tr>
    <td>TextBody</td>
    <td>{{.Data.Content}}</td>
</tr>

Am I missing something?

</div>
  • 写回答

2条回答 默认 最新

  • dotcraq3249 2016-08-06 13:49
    关注

    To print this in browser, replace with e.g. <br>
    like body = strings.Replace(body, " ", "<br>", -1)
    See this working sample code:

    package main
    
    import (
        "bytes"
        "fmt"
        "html/template"
        "log"
        "net/http"
        "strings"
    )
    
    func main() {
        http.HandleFunc("/", ServeHTTP)
        if err := http.ListenAndServe(":80", nil); err != nil {
            log.Fatal(err)
        }
    }
    
    func ServeHTTP(w http.ResponseWriter, r *http.Request) {
        html := `
    <!DOCTYPE html>
    <html>
    <body>  
    <table style="width:100%">
      <tr>
        <th>Data</th>
        <th>Content</th> 
      </tr> 
      <tr>
        <td>{{.Data}}</td>
        <td>{{.Content}}</td>
      </tr>
    </table> 
    </body>
    </html>
    `
        st := "Hi!
    How are you?
    Here is the link you wanted:
    http://www.google.com"
        data := DataContent{"data", st}
    
        buf := &bytes.Buffer{}
        t := template.Must(template.New("template1").Parse(html))
        if err := t.Execute(buf, data); err != nil {
            panic(err)
        }
        body := buf.String()
        body = strings.Replace(body, "
    ", "<br>", -1)
        fmt.Fprint(w, body)
    }
    
    type DataContent struct {
        Data, Content string
    }
    

    To see the output, run this code and open your browser at http://127.0.0.1/

    Also see: html/templates - Replacing newlines with <br>

    I hope this helps.

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

报告相同问题?

悬赏问题

  • ¥30 Matlab打开默认名称带有/的光谱数据
  • ¥50 easyExcel模板 动态单元格合并列
  • ¥15 res.rows如何取值使用
  • ¥15 在odoo17开发环境中,怎么实现库存管理系统,或独立模块设计与AGV小车对接?开发方面应如何设计和开发?请详细解释MES或WMS在与AGV小车对接时需完成的设计和开发
  • ¥15 CSP算法实现EEG特征提取,哪一步错了?
  • ¥15 游戏盾如何溯源服务器真实ip?需要30个字。后面的字是凑数的
  • ¥15 vue3前端取消收藏的不会引用collectId
  • ¥15 delphi7 HMAC_SHA256方式加密
  • ¥15 关于#qt#的问题:我想实现qcustomplot完成坐标轴
  • ¥15 下列c语言代码为何输出了多余的空格