0

Is it possible to render multiple html templates with the same name in golang. The reason is, that i want to make a layout and reuse it for multiple views. For example:

{{define "MainLayout"}}
<html>

  <head>
    <title>{{.Title}}</title>
  </head>

  <body>

    <div>{{template "Content" .}}</div>

  </body>

</html>
{{end}}

Content could be different templates, that all are defined by {{define "Content"}}

Sune
  • 607
  • 2
  • 8
  • 17
  • 1
    Possible duplicate of [How to use a field of struct or variable value as template name?](http://stackoverflow.com/questions/28830543/how-to-use-a-field-of-struct-or-variable-value-as-template-name) – icza Jan 16 '16 at 20:29
  • Go 1.6 will allow you to redefine blocks as per https://tip.golang.org/doc/go1.6#template - currently you can 'cheat' this with a bit of extra wrangling: http://elithrar.github.io/article/approximating-html-template-inheritance/ – elithrar Jan 16 '16 at 22:00

2 Answers2

0

I believe elithrar has what you are looking for, but unfortunately it's not currently supported. The typical way of handling this problem would be defining your header and footer in their own templates and doing the inverse of your approach. And you can pass the struct being given to the template parser into those templates to render your pages.

{{define "header"}}
<html>...
{{end}}

{{define "footer"}}
...</html>
{{end}}

{{define "Content"}}
{{template "header" .}}
HTML
{{template "footer" .}}
{{end}}
Sean
  • 1,048
  • 1
  • 11
  • 23
0

How are you parsing your templates? You can't have two templates with the same name in the same template tree. However, you could create a custom parsing function that will only add one template named "Content" to your template tree.

Example: https://play.golang.org/p/35X3i_jPzS

Zack
  • 71
  • 1
  • 5