如何在新行上打印“苹果”,“橙色”和“梨”?

Go:

const titlepage = `
<html>
<h1>{{ .Title}}</h1>
<h1>{{ range $i := .Body}}{{$i}}{{end}}</h1>
</html>
`
type tp struct {
    Title string
    Body []string
}

func Read() ([]string) {
    a := []string{"apple", "orange", "pear"}
    return a
}

func main() {
    as := tp{Title: "Hello", Body: Read()}
    t := template.Must(template.New("Tele").Parse(titlepage))
    t.Execute(os.Stdout, as)
}

电流输出:
<html>
<h1>Hello</h1>
<h1>appleorangepear</h1>
</html>

Go Playground上的代码:http://play.golang.org/p/yhyfcq--MM

最佳答案

模板中的换行符将被复制到结果中。如果要在{{$i}}之后添加换行符,只需添加一个。

编辑:如果希望换行符出现在Web浏览器中,则需要使用<br/>之类的HTML元素,或将项目放在<li>(列表)中。我在代码中添加了<br/>

http://play.golang.org/p/1G0CIfhb8a

const titlepage = `
<html>
<h1>{{ .Title}}</h1>
<h1>{{ range $i := .Body}}{{$i}}<br/>
{{end}}</h1>
</html>
`
type tp struct {
    Title string
    Body []string
}

func Read() ([]string) {
    a := []string{"apple", "orange", "pear"}
    return a
}

func main() {
    as := tp{Title: "Hello", Body: Read()}
    t := template.Must(template.New("Tele").Parse(titlepage))
    t.Execute(os.Stdout, as)
}

09-04 07:20
查看更多