2016-08-06 1 views
1

다음과 같은 내용의 MySQL에 일부 컨텐츠를 저장했습니다.골란 서식 파일에 새 줄을 인쇄하는 방법은 무엇입니까?

"Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com" 

Golang 템플릿으로 인쇄 할 때 올바르게 구문 분석하지 않습니다. 모든 것을 한 줄에 표시했습니다.

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

처럼 인쇄하는데 그 것은 여기 내 템플릿 코드입니다.

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

내가 누락 된 상품이 있습니까?

답변

1

브라우저에서 인쇄하려면 \n을 예 : html/templates - Replacing newlines with <br>

을 난이 도움이되기를 바랍니다 : 볼이 코드를 실행하고 또한 http://127.0.0.1/

에서 브라우저를 열고,

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!\nHow are you?\nHere is the link you wanted:\nhttp://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, "\n", "<br>", -1) 
    fmt.Fprint(w, body) 
} 

type DataContent struct { 
    Data, Content string 
} 

출력을 보려면 : body = strings.Replace(body, "\n", "<br>", -1)
같은 <br>
이 작업 샘플 코드를 참조하십시오 .

2

여기서 Split 함수를 사용하여 문자열을 구문 분석하고 sep을 구분 기호로 사용하여 부분 문자열을 조각으로 분할 할 수 있습니다.

package main 

import (
    "fmt" 
    "strings" 
) 

func main() { 
    txt := "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.google.com" 
    res := strings.Split(txt, "\n") 
    for _, val := range res { 
     fmt.Println(val) 
    } 
} 

출력 될 것이다 Go Playground

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

예.

+0

감사합니다. Simo,하지만 브라우저에서 인쇄하고 싶습니다. 이미 템플릿 헬퍼가 있습니까? – user1091558