V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
loading
V2EX  ›  Go 编程语言

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

  •  
  •   loading ·
    ycf · 2016-08-31 18:26:39 +08:00 · 850 次点击
    这是一个创建于 2803 天前的主题,其中的信息可能已经有所发展或是发生改变。
    事情是这样的,我在写一个报表类的应用,里面需要用到模版功能,就是把字符串:

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

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


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

    找到一个还没试用的库,似乎没活力了,不敢随便用。
    https://github.com/cloudfly/template
    7 条回复    2016-09-01 06:09:36 +08:00
    mind3x
        1
    mind3x  
       2016-08-31 18:59:48 +08:00   ❤️ 1
    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
        2
    loading  
    OP
       2016-08-31 19:03:04 +08:00 via Android
    @mind3x
    os.Stdout 似乎是 bytes stream ,不能是一个变量……
    hyq
        3
    hyq  
       2016-08-31 19:29:30 +08:00   ❤️ 1
    用 bytes.Buffer 就行
    hyq
        4
    hyq  
       2016-08-31 19:30:22 +08:00   ❤️ 1
    @loading bytes.Buffer 是一个 Writer ,替代那个 os.Stdout
    loading
        5
    loading  
    OP
       2016-08-31 21:00:27 +08:00 via Android
    @hyq 如果可以的话,可否给一个完整的,我还没太明白 golang 的这些东西……
    hyq
        6
    hyq  
       2016-09-01 01:55:17 +08:00   ❤️ 1
    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
        7
    loading  
    OP
       2016-09-01 06:09:36 +08:00 via Android
    @hyq 万分感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2436 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:20 · PVG 23:20 · LAX 08:20 · JFK 11:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.