簡體   English   中英

如何在Golang中使用不同的界面在一個網頁中執行多個模板?

[英]How to execute multiple templates in a single webpage using different interfaces in golang?

請原諒我一個奇怪的問題。 我不確定如何在單個語句中陳述我的問題。

我的網頁中有三個模板,頁眉,布局和頁腳。

在模板標題中,我有一個類別下拉菜單,並且在go代碼中有一片帶有子菜單項的字符串。

Categories := []string{"Holiday","IQ","Future"}

並且模板頭具有以下html代碼

<div class="ui dropdown item">
  <i class="browser icon"></i>
  Categories
  <i class="dropdown icon"></i>
  <div class="menu">              
    {{range $i,$e:= .}}
    <a class="item"><i class="hashtag icon"></i>{{$e}}</a>
    {{end}}
  </div>
</div>

所以當我做一個

t,err :=template.ParseFiles("template/header.html","template/index.html","template/footer.html")
t.ExecuteTemplate(w,"header",Categories)

它給了我一個漂亮的標題,但我需要做

t.ExecuteTemplate(w,"layout",Featured)

用於主頁。 布局模板具有以下結構

some html code
{{template "header"}}
more html code
{{template "footer"}}

顯然,將兩個execute模板語句一起使用給了我兩個不同的標題。

如果我從模板布局中刪除模板標題,則視覺輸出是完美的,但是當您查看html代碼時,菜單欄位於“ link rel”語句上方(請記住,我在{{template“上方有“一些html代碼”標頭”}}(在布局模板中),這顯然不好。

我應該怎么做才能使兩個模板都使用各自的結構同時執行?

我決定編輯標題模板,使其也包含其上方的所有內容,並相應地更改了go代碼。 實際上,我上面有一些CSS和腳本參考。 由於每個頁面都會有所不同,因此我僅在標題中包含nav_bar,但我想出了解決此問題的方法。

我做了一個新的結構

type Header struct{
    Css []string;
    Title string;
    Js []string;
    Categories []string;
}

這是我的標題模板的一部分

{{range $i,$e:=.Css}}
<link rel="stylesheet" type="text/css" href="{{$e}}">
{{end}}
{{range $i,$e:=.Js}}
<script src="{{$e}}"></script>
{{end}}

我首先使用相應的標頭接口對標頭進行執行模板部分,然后使用其相應的接口對另一個執行模板進行處理。 另外我還必須從index.html中刪除{{template“ header”}}部分。 結果現在看起來很完美,並且按照我想要的方式工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM