go-templates

How to calculate something in html/template

佐手、 提交于 2020-01-25 07:31:12
问题 How can you calculate something inside a html template of go? For example: {{ $length := len . }} <p>The last index of this map is: {{ $length -1 }} </p> Were the . is a map. The code {{ $length -1 }} is not working, is there a way to achieve this? 回答1: You can't. Templates are not a scripting language. By design philosophy, complex logic should be outside of templates. Either pass the calculated result as a parameter (preferred / easiest), or register custom functions which you can call

Go template name

两盒软妹~` 提交于 2020-01-09 03:49:06
问题 In the html/template (and text/template ) packages, template.New has the following signature: func New(name string) *Template What exactly is the name used for? I've scanned the docs (and a bit of source), but to no avail. I just instantiate all of my templates with an empty string and it doesn't seem to make a difference. Why should I bother with a name? Even for naming templates, the two seem equivalent: template.Must(template.New("").Parse(`{{ define "body" }}Body{{ end }}`)) template.Must

Golang embed html from file

强颜欢笑 提交于 2020-01-03 09:07:10
问题 How can I do in Golang if I have an HTML file like this: <html> <head lang="en"> </head> <body> <header>{{.Header}}</header> <div class="panel panel-default"> </div> </body> </html> and I want to embed a part of code into to header tags from an other file like this: <div id="logo"></div><div id="motto"></div> My try: header, _ := template.ParseFiles("header.html") c := Content{Header: ""} header.Execute(c.Header, nil) index := template.Must(template.ParseFiles("index.html")) index.Execute(w,

Go template function

时光怂恿深爱的人放手 提交于 2019-12-31 17:49:27
问题 It noticed a weird thing with Go templates when I try to use Funcs and FuncMap . The following code works as expected: buffer := bytes.NewBufferString("") funcMap := template.FuncMap{ "label": strings.Title, } t, _ := template.New("alex").Funcs(funcMap).Parse("{{label \"alex\"}}") t.Execute(buffer, "") return string(buffer.Bytes()) //=> "Alex" But when I try to put the template in a file, it does not work ( Execute() says: "alex" is an incomplete or empty template ): t, _ := template.New(

Go template remove the last comma in range loop

巧了我就是萌 提交于 2019-12-30 06:11:56
问题 I have code like this: package main import ( "text/template" "os" ) func main() { type Map map[string]string m := Map { "a": "b", "c": "d", } const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}` t := template.Must(template.New("example").Parse(temp)) t.Execute(os.Stdout, m) } it will output : key:a value:b,key:c value:d, but I want something like this: key:a value:b,key:c value:d I don't need the last comma, how to remove it. I found a solution for looping an array

get the value of a go template from inside another template [duplicate]

痞子三分冷 提交于 2019-12-24 19:16:48
问题 This question already has an answer here : Capture or assign golang template output to variable (1 answer) Closed last year . I have two templates T1 and T2. I want to get the output of T1 and do a some extra processing on it inside T2. My question is: how do I store the output of T1 in a variable inside T2? Is this even possible? Here's some pseudo-template: {{define "T1"}} {{ printf "%s-%s" complex stuff }} {{end}} {{define "T2"}} {{ $some_var := output_from_template "T1"}} <<<<<<<<<<< {{

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

邮差的信 提交于 2019-12-24 16:13:59
问题 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

How do I access object field by variable in template?

半腔热情 提交于 2019-12-24 01:48:06
问题 I have a nested loop: {{$columns := .columns}} {{range $dx := .dataList}} {{range $c := $columns}} {{index $dx $c}} {{end}} {{end}} dataList is the orm model array. With ID, Title fields , then columns is the []string variable contains all orm model field names like ID, Title . type AdFile struct { ID uint `gorm:"primary_key"` Title string } I've tried with {{(index .listData 0).Title}} and it works. But if i want to access $dx.Title , $dx.ID .... with Title , ID as variables, but it doesn't

Show default content in a template if an object is nil otherwise show based on the set property

蹲街弑〆低调 提交于 2019-12-22 07:00:28
问题 In my template, I would like to include some default meta tags (90% of the time). However, when a specific property is set, I would like to show a different set of text. I know I can set an anonymous struct and set a property with either "default" or "some-x" . However, this means, I need to add an anonymous struct to 90% of my handlers that just currently pass nil . Is there way to do something like {{if eq . nil}} // default meta tag {{else if eq .MetaValue "some-x"}} //other {{end}} If I

How to print JSON on golang template?

若如初见. 提交于 2019-12-21 03:44:31
问题 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) }, 回答1: In JS