Reputation: 64944
I've loaded a template file into memory with the following code:
t := template.New("master")
tpl, err := t.ParseFiles("templates/index.html")
Now I want to draw that template into a string, so my index.html
is pretty empty:
{{define "master"}}
Hello World
{{end}}
I'm just starting out, so I don't have any data yet. Is there a way I can convert the Template
object into a string without data?
Upvotes: 2
Views: 972
Reputation: 41805
If your template doesn't (yet) use any variables, you can just pass any value as data to render the template. So, to render the template to stdout, you could for example use:
tpl.Execute(os.Stdout, nil)
If you really want to render the template to a string, you can use a bytes.Buffer
as an intermediary:
var buf bytes.Buffer
tpl.Execute(&buf, nil)
str := buf.String()
Upvotes: 4
Reputation: 64944
This is impossible in Go, by design - if you don't have data, the Template package is unnecessary overhead.
If you have no data, just read the file using the io
package, instead of using templates.
Upvotes: -1