* 'Sergey Krutsko' via golang-nuts <golang-nuts@googlegroups.com> [161208 02:12]: > Thanks Marvin! > > that's exactly what i need > > bwt, is there any way to get current timestamp inside the template (without > referencing to the data structure) ? > > something like that: > "timestamp: {{time.Now.Unix}}"
You can use a template.FuncMap. If, by "without referencing to the data structure", you mean without adding anything additional to the data structure, then you will have to use a FuncMap. If you mean "without adding the current time as a value to the data structure", but will allow adding functions to the data structure, then there is another way. Add a field (or map element) to the data of some func type (e.g. func() time.Time) and use call inside the template. The playground link https://play.golang.org/p/9rsVDBPzy2 demonstrates both methods. When using a FuncMap, it must be defined on the template (with a call to Funcs) before parsing any template that uses it. If you are using ParseFiles or ParseGlob, rather than Parse, this is a little tricky, and the template documentation could be improved significantly to address the issue. The helper functions ParseFiles and ParseGlob (at the package level, rather than the methods on *Template) cannot be used because there is no way to pass a FuncMap before parsing. If you try something like var t, err = template.New("").Funcs(fm).ParseFiles(file) // handle error, then... err = t.Execute(os.Stdout, data) you will get an error containing ... "" is an incomplete or empty template;... The problem is that t is an empty template with name "", and the template(s) resulting from ParseFiles is only an associated template with a name derived from the file name. So t.Execute() attempts to execute the empty template. There are at least two ways to make it work. One way is to replace the first line above with var t, err = template.New(filepath.Base(file)).Funcs(fm).ParseFles(file) and the other is to replace the Execute line above with err = t.ExecuteTemplate(os.Stdout, t.Templates()[0].Name(), data) A third way would be to use ioutil.ReadFile to read the whole file and then call t.Parse on the string obtained from that. Using this method, the result of Parse is used as the template t, not as an associated template with a different name. ...Marvin -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.