Pass data via main template to sub template?

I have passed data to a one level template with success.

main.go

	path := strings.Trim(r.URL.Path, "/")
	page = page + ".html"
    list := Get(query)
	err := tpl.ExecuteTemplate(w, page, list)

posts.html

<!DOCTYPE html>
<html data-theme="classic" lang="en">

  <head>
    {{template "httphead"}}
  </head>
  <body>
    <div class="content">
      <table>
        <col style="width:50px">
        <col style="width:100%">
        {{range .}}
        <tr>
          <td><img src="avatar/{{.Id}}.jpg"></td>
          <td>
            <h4>#{{.Id}} {{.Subject}}</h4>
            <p>John Doe</p>
          </td>
        </tr>
        {{end}}
      </table>
    </div>
  </body>
</html>

But this approach does not work with using themes. As each template has its own <html data-theme="classic">, there is a delay when setting the theme.

Live: http://94.237.92.101:2020/posts (this works but themes are delayed)

So now I am trying to do ONE main html template

layout.html

<!DOCTYPE html>
<html data-theme="" lang="en">
  {{template "httphead"}}

  <body>
    <div class="mainbox">
      {{template "header"}}
      <div class="contentbox">
        {{template "content" .}}
      </div>
    </div>
  </body>

</html>

and separate sub templates for data:

posts.html

<div class="contentbox">
    <div class="content">
      <table>
        <col style="width:50px">
        <col style="width:100%">
        {{range .}}
        <tr>
          <td><img src="avatar/{{.Id}}.jpg"></td>
          <td>
            <h4>#{{.Id}} {{.Subject}}</h4>
          </td>
        </tr>
        {{end}}
      </table>
    </div>
  </div>
</div>

and in the main.go

page = page + ".html"

layout := tpl.Lookup("layout.html")
layout, _ = layout.Clone()
t := tpl.Lookup(page)
_, _ = layout.AddParseTree("content", t.Tree)
layout.Execute(w, page, list)  <--- Not able to pass data

./main.go:72:16: too many arguments in call to layout.Execute
have (http.ResponseWriter, string, interface {})
want (io.Writer, interface {})

Live http://94.237.92.101:3030/posts (no data passed)

  1. How do I pass data via the main template?
  2. Is there any better way to do this?

Do you want to pass the name of a template as the second argument?

Did you try Template.ExecuteTemplate instead of Template.Execute?

layout.ExecuteTemplate(w, page, list)

Only render the sub template. The data is transfered.

tpl.ExecuteTemplate(w, page, list)

Only render the main template. No data is transfered

How do I render both main and sub template?

The solution was simpler than I thougth:

layout.Execute(w, list)

http://94.237.92.101:3030/posts

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.