如何在Mustache模板中将字符串转换为帕斯卡命名法?
问题:Go语言中Mustache模板实现首字母大写输出
现有Mustache模板
{{#attributes}} func (event {{fileNameRoot}}) Get{{Name}}() string { return event.{{Name}} } {{/attributes}}
当前输出结果
func (event JustATest) GetuserName() string { return event.userName }
期望输出结果
func (event JustATest) GetUserName() string { return event.UserName }
我的Go代码
data := map[string]interface{}{ "fileNameRoot": "JustATest", "attributes": schema.Attributes, } out, err := mustache.RenderFile("templates/test.go.mustache", data) if err != nil { panic(err) }
解决方案
由于github.com/hoisie/mustache没有内置首字母大写的过滤器,需要在Go代码中预处理数据,为每个属性生成首字母大写的字段,再修改模板引用该字段。
步骤1:预处理属性数据
假设schema.Attributes是包含Name字段的结构体切片,遍历并生成首字母大写的字段:
import "strings" // 假设Attribute结构体定义如下 // type Attribute struct { // Name string // } processedAttrs := make([]map[string]interface{}, len(schema.Attributes)) for i, attr := range schema.Attributes { // 将Name首字母大写 upperName := strings.ToUpper(string(attr.Name[0])) + attr.Name[1:] processedAttrs[i] = map[string]interface{}{ "Name": attr.Name, "UpperName": upperName, } }
步骤2:更新数据映射
将原attributes替换为预处理后的切片:
data := map[string]interface{}{ "fileNameRoot": "JustATest", "attributes": processedAttrs, }
步骤3:修改Mustache模板
将模板中的{{Name}}替换为{{UpperName}}:
{{#attributes}} func (event {{fileNameRoot}}) Get{{UpperName}}() string { return event.{{UpperName}} } {{/attributes}}
执行以上修改后,模板输出即可符合期望。
内容的提问来源于stack exchange,提问作者Akash Rastogi
相关产品推荐
相关产品推荐

