【问题标题】:Golang & Martini code blockGolang & Martini 代码块
【发布时间】:2015-05-04 14:50:38
【问题描述】:

我正在尝试定义代码块,如果它们被定义,它们将被注入到基本模板中。我不想将一个页面上需要的所有脚本都包含到另一个不需要它的页面上。

我正在使用:

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

【问题讨论】:

  • 请在代码中显示您访问模板的位置
  • 见这里 - elithrar.github.io/article/… - 你可以在你的模板中定义“可选”块,方法是在你的基本内容中使用``{{ define XXX }}` 它们,但不要让它们为空。

标签: html go martini


【解决方案1】:

我知道这违反直觉,但出于性能原因,最好将所有 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}}
    

【讨论】:

    猜你喜欢
    • 2015-10-23
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 2014-04-29
    相关资源
    最近更新 更多