0

I'm trying to get into web-development in Go, and so far I've figured out to nest templates and passing in variables. But is there a way to reuse templates? I'm thinking along the lines of creating a new template from an existing one, and passing in variables unique for each.

Take for instance this template:

{{define "btn"}}
<button type={{.Type}} class={{.Class}} title={{.Title}}>
    {{.Name}}
</button>
{{end}}

Would the be a way to create new static templates from "btn", and use them somewhat like this:

<html>
  <head>
    <title>My page</title>
  </head>
  <body>
    <h1>A button</h1>
    <div>{{template "btn-version-1"}}</div>
    </div>
    <h2>Another button</h2>
    <div>Some content {{template "btn-version-2"}}</div>
  </body>
</html>

But I feel that I'm barking up the wrong tree.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 2
    https://golang.org/pkg/text/template/#hdr-Nested_template_definitions – Adrian Feb 28 '20 at 21:21
  • Thanks for the pointer. I can see I was looking in the wrong direction. " If it's necessary to have a template addressable from multiple associations, the template definition must be parsed multiple times to create distinct *Template values, or must be copied with the Clone or AddParseTree method." –  Feb 28 '20 at 21:36

0 Answers0