Golang和Martini代码块

I am trying to define code blocks that will get injected in the base template if they are defined. I don't want to include all the scripts that are required on one page onto another that doesn't require it.

I am using:

"github.com/go-martini/martini"
"github.com/martini-contrib/binding"
"github.com/martini-contrib/render"

Basically what im trying to do is something like:

on the layout: admin.tmpl:

<script src="jquery.min.js"></script>
<script src="scripts.min.js"></script>
{{ footer_extra }}

and on new.tmpl:

{{define "footer_extra"}}
  <!-- scripts just for this page -->
  <script src="script-1.js"></script>
  <script src="script-2.js"></script>
  <script src="script-3.js"></script>
{{end}}

It seemed to work when I used template instead.

But I noticed that I can't define more than one template, which kinda defeats what I'm trying to achieve.

index.tmpl

{{define "footer_extra"}}
  <!-- scripts just for this page -->
  <script src="script-1.js"></script>
  <script src="script-2.js"></script>
{{end}}

new.tmpl

{{define "footer_extra"}}
  <!-- scripts just for this page -->
  <script src="script-3.js"></script>
  <script src="script-4.js"></script>
{{end}}

layout.tmpl

<script src="main.js"></script>
{{template "footer_extra"}}

will throw a PANIC template: redefinition of template "footer_extra"

I know it's counterintuitive, but for performance reasons it's better to bundle all of your javascript into a few files and include them on every page.

But if you still want to do this, there are two ways you can solve the problem:

  1. Give the other footer_extra a different name and then reference it explicitly in your template:

    <script src="jquery.min.js"></script>
    <script src="scripts.min.js"></script>
    {{ admin_footer_extra }}
    
  2. Make the footer part of the data you send to the template:

    var buf bytes.Buffer
    // or ParseFiles if that's how you're reading these
    tpl := template.Must(template.New("").Parse(tpls))
    // render the footer
    tpl.ExecuteTemplate(&buf, "footer_extra", nil)
    footer := buf.String()
    buf.Reset()
    // send the footer to the main template
    tpl.ExecuteTemplate(&buf, "index", map[string]interface{}{
        "Footer": template.HTML(footer), 
                        //  ^   this makes it so go won't escape < & >
    })
    

    Then your template will just have:

    {{define "page1"}}
      {{.Footer}}
    {{end}}