英文:
Go: Print each element in slice on new line with html/template
问题
如何在新行上打印"apple"、"orange"和"pear"?
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
英文:
How do I print "apple", "orange", and "pear" on a new line?
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)
}
Current output:
<html>
<h1>Hello</h1>
<h1>appleorangepear</h1>
</html>
The code on Go Playground: http://play.golang.org/p/yhyfcq--MM
答案1
得分: 4
模板中的换行符将被复制到结果中。如果你想在{{$i}}
之后换行,只需添加一个换行符。
编辑:如果你想在网页浏览器中显示换行符,你需要使用像<br/>
这样的HTML元素,或者将你的项目放在<li>
(列表)中。我在代码中添加了一个<br/>
。
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)
}
你可以在这里查看代码的运行结果:http://play.golang.org/p/1G0CIfhb8a
英文:
Newline characters from the template will be copied into the result. If you want a newline after {{$i}}
, you just need to add one.
Edit: If you want a newline to appear in the web browser, you need to use an HTML element like <br/>
, or put your items in a <li>
(list). I added a <br/>
to the code.
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论