Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining quoted, comma-separated strings (given a list of structs containing those strings)

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 ? :

  • I shouldn't add any too specific template function (e.g. one that joins and quotes .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)
like image 205
Nicolas Marshall Avatar asked Sep 02 '25 15:09

Nicolas Marshall


1 Answers

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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!