Golang 的 text/template 能不能用于字符串处理?

2016-08-31 18:26:39 +08:00
 loading
事情是这样的,我在写一个报表类的应用,里面需要用到模版功能,就是把字符串:

"全班一共{{ count_person }}人,其中有{{ count_passed }}人及格,班主任是{{ teacher_name }}"

这样的字符串,想用 web 模板那样,通过传参数的方式,进行替换,查了一下似乎没有这样的用法?(还在面向 google 开发中,请指正)


求教这样的需求一般使用什么方法呢?难道用我还是蒙逼状态的正则?
求 demo 代码?

找到一个还没试用的库,似乎没活力了,不敢随便用。
https://github.com/cloudfly/template
871 次点击
所在节点    Go 编程语言
7 条回复
mind3x
2016-08-31 18:59:48 +08:00
https://golang.org/pkg/text/template/
一开始就有 example 啊...

Here is a trivial example that prints "17 items are made of wool".

```
type Inventory struct {
Material string
Count uint
}
sweaters := Inventory{"wool", 17}
tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")
if err != nil { panic(err) }
err = tmpl.Execute(os.Stdout, sweaters)
if err != nil { panic(err) }
```
loading
2016-08-31 19:03:04 +08:00
@mind3x
os.Stdout 似乎是 bytes stream ,不能是一个变量……
hyq
2016-08-31 19:29:30 +08:00
用 bytes.Buffer 就行
hyq
2016-08-31 19:30:22 +08:00
@loading bytes.Buffer 是一个 Writer ,替代那个 os.Stdout
loading
2016-08-31 21:00:27 +08:00
@hyq 如果可以的话,可否给一个完整的,我还没太明白 golang 的这些东西……
hyq
2016-09-01 01:55:17 +08:00
package main

import "text/template"
import "fmt"
import "bytes"

type Class struct{
CountPersion uint32
CountPassed uint32
TeacherName string
}

func main() {
str := "全班一共{{ .CountPersion }}人,其中有{{ .CountPassed }}人及格,班主任是{{ .TeacherName }}"
tpl := template.Must(template.New("test").Parse(str))
b := &bytes.Buffer{}
tpl.Execute(b, &Class{1,2,"Lili"})

fmt.Println(b.String())
}
loading
2016-09-01 06:09:36 +08:00
@hyq 万分感谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/302987

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX