Using go templates, I've been trying to render a list of quoted, comma-separated strings
e.g. "string1", "string2", "string3"
The strings I want to render come from a slice of structs. See the Tags in this example:
package main
import (
"fmt"
"log"
"os"
"strings"
"text/template"
)
const (
templateString = `{{range .Tags}}"{{.Name}}", {{end}}`
)
var (
funcs = template.FuncMap{
"join": strings.Join,
"quote": func(in string) string { return fmt.Sprintf("\"%s\"", in) },
}
renderData = Task{
Name: "something to do",
Description: "Do that thing",
Tags: &[]Tag{
Tag{Name: "tag1"},
Tag{Name: "tag2"},
},
}
)
func main() {
tmpl, err := template.New("master").Funcs(funcs).Parse(templateString)
if err != nil {
log.Fatal(err)
}
if err := tmpl.Execute(os.Stdout, renderData); err != nil {
log.Fatal(err)
}
}
type Task struct {
Name string
Description string
Tags *[]Tag
}
type Tag struct {
Name string
}
See it in the playground
How could this be done, given the following constraint ? :
.Names for Tags) (because my users will only be able to edit templates, not Go-code/template-functions, I should try and solve the problem with the same tools, which means templates and maybe very generic functions)Use an {{if}} to print the comma only when needed. Add the quotes directly to the template:
templateString = `{{range $i, $v := .Tags}}{{if $i}} ,{{end}}"{{.Name}}"{{end}}`
playground example
If you want to escape " in the name, then use the built-in printf function to quote the string:
templateString = `{{range $i, $v := .Tags}}{{if $i}} ,{{end}}{{printf "%q" .Name}}{{end}}`
playground example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With