2015-05-04 48 views
0

我想定義代碼塊,如果它們被定義,它們將被注入基本模板。我不想將所有需要在一個頁面上的腳本包含到另一個不需要的腳本中。Golang&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"

+0

請在你的代碼顯示的地方,你要訪問您的模板 –

+0

看到這裏 - http://elithrar.github.io/article/approximating-html -template-inheritance/- 你可以在你的模板中通過「{{define XXX}}」來定義它們,但是讓它們爲空。 – elithrar

回答

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