dongxianchu3541 2016-03-20 13:34
浏览 24
已采纳

在Goe GAE上显示html / template产生的换行符

My application is written in Go. A page of the application receives user data from an HTML text area which is saved to Google App Engine datastore as string data. Then, on another page of the application, it requires to display the data in the format that the user typed into the HTML text area or at least preserve the line breaks as the user hit enter key while typing the data into the HTML text field.

I tried to use <pre> tag to display the preserved line breaks that user typed into the text field which worked fine. However, I found that there is a double tab

\t\t

inserted at the beginning of the string when using the <pre> tag which I could remove the double tab by using Javascript.

My idea to keep the line breaks that users type into the text field is to use javascript replace function to replace all , and to <br>, however, it didn't work out. It seems like Go doesn't output the line breaks into the html source code. I am using "html/template" for safety reason but I didn't expect it to remove the characters from its output entirely. And is there any suggestion on the strange double tab \t\t at the beginning to the string?

  • 写回答

2条回答 默认 最新

  • duanrang9348 2016-03-20 13:46
    关注

    Instead of changing the newlines to <br> in javascript, do it in Go: http://play.golang.org/p/jJXMZxtYcv

    package main
    
    import (
        "html/template"
        "log"
        "os"
        "strings"
    )
    
    func main() {
        const tpl = `
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>{{.Title}}</title>
        </head>
        <body>
            <div>{{nl2br .Text}}</div>
        </body>
    </html>`
    
        check := func(err error) {
            if err != nil {
                log.Fatal(err)
            }
        }
    
        funcs := template.FuncMap{
            "nl2br": func(text string) template.HTML {
                return template.HTML(strings.Replace(template.HTMLEscapeString(text), "
    ", "<br>", -1))
            },
        }
    
        t, err := template.New("webpage").Funcs(funcs).Parse(tpl)
        check(err)
    
        data := struct {
            Title string
            Text  string
        }{
            Title: "My page",
            Text:  "\t\tLine 1
    Line2
    ",
        }
    
        err = t.Execute(os.Stdout, data)
        check(err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥50 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗