Golang Go语言中 text/template 是否能用于字符串处理?

事情是这样的,我在写一个报表类的应用,里面需要用到模版功能,就是把字符串:

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

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


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

找到一个还没试用的库,似乎没活力了,不敢随便用。
https://github.com/cloudfly/template
Golang Go语言中 text/template 是否能用于字符串处理?

8 回复

https://golang.org/pkg/text/template/
一开始就有 example 啊…

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

<br>type Inventory struct {<br> Material string<br> Count uint<br>}<br>sweaters := Inventory{"wool", 17}<br>tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}}")<br>if err != nil { panic(err) }<br>err = tmpl.Execute(os.Stdout, sweaters)<br>if err != nil { panic(err) }<br>

更多关于Golang Go语言中 text/template 是否能用于字符串处理?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html



os.Stdout 似乎是 bytes stream ,不能是一个变量……

用 bytes.Buffer 就行

bytes.Buffer 是一个 Writer ,替代那个 os.Stdout

如果可以的话,可否给一个完整的,我还没太明白 golang 的这些东西……

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())
}

万分感谢

在Golang(Go语言)中,text/template 包主要用于文本模板的生成和处理,它并不是专门设计用于字符串处理的通用工具。然而,text/template 确实可以在某种程度上用于字符串的格式化和替换,尤其是当你需要基于一些数据动态生成文本时。

text/template 允许你定义包含变量和动作的模板,然后通过执行这些模板来生成最终的文本输出。变量可以通过数据传递给模板进行替换,动作则允许你执行一些控制结构(如条件判断和循环)。

虽然 text/template 能够处理字符串(模板本身就是字符串),但如果你只是需要进行简单的字符串操作(如拼接、查找、替换等),Go 标准库中的 strings 包是更合适的选择。strings 包提供了丰富的函数来直接处理字符串,这些函数通常更高效且易于使用。

总结来说,虽然 text/template 可以用于生成和处理包含变量的字符串模板,但如果你只是需要进行基本的字符串操作,建议使用 strings 包。text/template 更适合用于复杂的文本生成场景,其中需要嵌入变量和控制结构来动态生成内容。因此,在选择工具时,请根据你的具体需求来决定是使用 text/template 还是 strings 包。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!