2

I have a base.html template stored in the file, with the following content:

<!doctype HTML>
<html>
<head>
  <title>{{ template "title" }}</title>
</head>
<body>
  {{ template "content" }}
</body>

Also I have a template post.html to fill in the content section of base.html template:

{{ define "title" }} Title {{ end }}
{{ define "content" }}
<p>Here is my content</p>
{{ end }}

I know how to combine the templates if these two templates are stored on disk as HTML files. I do something like this:

t, _ := template.ParseFiles(basePath, postPath)
t.ExecuteTemplate(w, "base", nil)

However, I also have a use case when I want to combine two templates, where one of them comes from the file and another one - from a string. For example:

baseTemplate, _ := template.ParseFiles(basePath)
contentTempalte, _ := template.New("content").Parse(`
{{ define "content" }}
<p>Here is my content</p>
{{ end }}
`)
// Is it possible to do something like this made up function?
// baseTemplate.ExecuteWith(os.Stdout, contentTemplate, nil)

I wonder if it possible to combine these two templates somehow together? Or any arbitrary instances of template.Template? I've never worked with Golang templates before, so the process is still a bit unclear to me.

devforfu
  • 1,570
  • 1
  • 19
  • 41

0 Answers0