go-templates

How to print JSON on golang template?

老子叫甜甜 提交于 2019-12-03 12:14:52
I need a object in client side, so I converted it to JSON using json.marshal and printed it into template. The object is getting printed as escaped JSON string. I'm expecting it to be var arr=["o1","o2"] but it is var arr="[\"o1\",\"o2\"]" I know I can JSON.parse in client side, but is that the only way? Here is how I'm printing it in template: {{ marshal .Arr }} Here is my marshal function: "marshal": func(v interface {}) string { a, _ := json.Marshal(v) return string(a) }, In JS context normal strings always gets escaped. I should have converted to template.JS type before printing. Ref: http

How to range over slice of structs instead of struct of slices

◇◆丶佛笑我妖孽 提交于 2019-12-03 06:29:47
Having played around with Go HTML templates a bit, all the examples I found for looping over objects in templates were passing structs of slices to the template, somewhat like in this example : type UserList struct { Id []int Name []string } var templates = template.Must(template.ParseFiles("main.html")) func rootHandler(w http.ResponseWriter, r *http.Request) { users := UserList{ Id: []int{0, 1, 2, 3, 4, 5, 6, 7}, Name: []string{"user0", "user1", "user2", "user3", "user4"}, } templates.ExecuteTemplate(w, "main", &users) } with the "main" template being : {{define "main"}} {{range .Name}} {{.}

How can you call a helm 'helper' template from a subchart with the correct context?

断了今生、忘了曾经 提交于 2019-12-03 02:57:18
Helm charts define helper templates in _helpers.tpl which are used to create normalized names for the services. The standard form of the template for a service (DNS) name is: {{- define "postgresql.fullname" -}} {{- $name := default .Chart.Name .Values.nameOverride -}} {{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}} {{- end -}} If using postgresql as a subchart, how are you supposed to use DNS-based service discovery to refer to it? A common pattern seems to be to copy the subchart helpers into the parent chart. {{- define "keycloak.postgresql.fullname" -}} {{- $name :=

Ouput json to http.ResponseWriter with template

丶灬走出姿态 提交于 2019-12-02 13:19:51
i've this template: var ListTemplate = ` { "resources": [ {{ StringsJoin . ", " }} ] } ` rendered with: JoinFunc := template.FuncMap{"StringsJoin": strings.Join} tmpl := template.Must(template.New("").Funcs(JoinFunc).Parse(ListTemplate)) if i send it to a http.ResponseWriter the output text is escaped. var list []string tmpl.Execute(w, list) how can i write a json this way? You shouldn't use Go's template engine (neither text/template nor html/template ) to generate JSON output, as the template engine has no knowledge of JSON syntax and rules (escaping). Instead use the encoding/json package

Go can't evaluate field when using range to build from template

孤街浪徒 提交于 2019-12-02 06:57:36
I have Files slice of File structure in my Go program to keep name and size of files. I created template, see below: type File struct { FileName string FileSize int64 } var Files []File const tmpl = ` {{range .Files}} file {{.}} {{end}} ` t := template.Must(template.New("html").Parse(tmplhtml)) err = t.Execute(os.Stdout, Files) if err != nil { panic(err) } Of course I got panic saying: can't evaluate field Files in type []main.File Not sure how to correctly display file names and sizes using range in template. The initial value of your pipeline (the dot ) is the value you pass to Template

How to pass multiple values from template to template?

社会主义新天地 提交于 2019-12-02 05:18:37
问题 My City struct is like this: type City struct { ID int Name string Regions []Region } And Region struct is: type Region struct { ID int Name string Shops []Destination Masters []Master EducationCenters []Destination } In main I try to do this: tpl.ExecuteTemplate(resWriter,"cities.gohtml",CityWithSomeData) Is it possible to do something like this inside template? {{range .}} {{$city:=.Name}} {{range .Regions}} {{$region:=.Name}} {{template "data" .Shops $city $region}} {{end}} {{end}} 回答1:

How to indent content of included template

别来无恙 提交于 2019-12-02 00:54:36
I am using go templates to create yaml definitions for kubernetes. I am trying to nest templates but run into issues where I can't re-use a definition simply because the indention is wrong when included. I.e., in one case the contents need indentation but do not in another. How can I control the indention of included content? Example below. I am reusing pod.tmpl, in the first case it can be included as is. In the second case I need to indent the entire contents so it becomes member of service {{ if (eq .Case "pod") # NO indenting {{ template "pod" }} {{ end }} {{ if (eq .Case "service")

detect last item inside an array using range inside go-templates

无人久伴 提交于 2019-12-01 17:28:41
This program outputs simply 1,4,2, but I would like to print 1,4,2. As you can see the comma is printed after each items of an array. package main import "os" import "text/template" func main() { params := map[string]interface{}{ "items": [3]int{1, 4, 2}, } tpl := "{{range $i, $el := .items}}{{$el}},{{end}}" lister, _ := template.New("foo").Parse(tpl) lister.Execute(os.Stdout, params) } Is there a way to change {{range $i, $el := .items}}{{$el}},{{end}} and be sure that last item will print "." instead of "," You can use tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}." to

How to get a map or list of template 'actions' from a parsed template?

随声附和 提交于 2019-12-01 11:08:54
So I would like to somehow get all of my {{ .blahblah }} actions defined in a template as slice of strings. For example if I have this template: <h1>{{ .name }} {{ .age }}</h1> I would like to be able to get []string{"name", "age"} . Pretend that a template has the method func (t *Template) Fields() []string : t := template.New("cooltemplate").Parse(`<h1>{{ .name }} {{ .age }}</h1>`) if t.Fields() == []string{"name", "age"} { fmt.Println("Yay, now I know what fields I can pass in!") // Now lets pass in the name field that we just discovered. _ = t.Execute(os.Stdout, map[string]string{"name":

How to get a map or list of template 'actions' from a parsed template?

匆匆过客 提交于 2019-12-01 07:26:53
问题 So I would like to somehow get all of my {{ .blahblah }} actions defined in a template as slice of strings. For example if I have this template: <h1>{{ .name }} {{ .age }}</h1> I would like to be able to get []string{"name", "age"} . Pretend that a template has the method func (t *Template) Fields() []string : t := template.New("cooltemplate").Parse(`<h1>{{ .name }} {{ .age }}</h1>`) if t.Fields() == []string{"name", "age"} { fmt.Println("Yay, now I know what fields I can pass in!") // Now