Golang& Martini代码块

时间:2015-05-04 14:50:39

标签: html go martini

我正在尝试定义将在基本模板中注入的代码块(如果已定义)。我不希望将一个页面上所需的所有脚本包含到另一个不需要它的脚本中。

我正在使用:

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

基本上我试图做的是:

布局上的

admin.tmpl

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

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}}

当我使用模板时它似乎有效。

但我注意到我无法定义多个模板,这有点挫败了我想要达到的目标。

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"}}

将抛出PANIC template: redefinition of template "footer_extra"

1 个答案:

答案 0 :(得分:0)

我知道这是违反直觉的,但出于性能原因,最好将所有javascript捆绑到几个文件中并将其包含在每个页面中。

但如果您仍想这样做,有两种方法可以解决问题:

  1. 为其他footer_extra提供不同的名称,然后在模板中明确引用它:

    <script src="jquery.min.js"></script>
    <script src="scripts.min.js"></script>
    {{ admin_footer_extra }}
    
  2. 使您发送到模板的数据的页脚部分:

    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 < & >
    })
    

    然后你的模板就会有:

    {{define "page1"}}
      {{.Footer}}
    {{end}}
    
相关问题