douzhi4991 2016-12-23 14:55
浏览 24
已采纳

如何在Golang中使用不同的界面在一个网页中执行多个模板?

Please forgive me for a weird looking question. I wasn't sure exactly how to state my problem in a single statement.

I have three templates in my webpage, header, layout and footer.

In the template header, I have a categories dropdown menu and I have a slice of strings with sub-menu items in my go code.

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

and the template header has following html code

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

so when I do a,

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

It gives me a nice looking header but I need to do

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

for the main page. Layout template has the following structure

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

Using both the execute template statements together gives me two different headers,obviously.

If I remove template header from the template layout, the visual output is perfect but when you look at the html code, the menu bar is above the "link rel" statements(remember,I had 'some html code' above {{template "header"}} in the layout template) and that is obviously not good.

What should I do so that both the templates are executed simultaneously using their respective structs?

  • 写回答

1条回答 默认 最新

  • donglinyi4313 2016-12-23 18:06
    关注

    I decided to edit my header template to include everything above it as well and changed my go code accordingly. I actually had some css and script references above it. Since it was going to be different for every page, I only included the nav_bar in the header but I figured out to fix this problem.

    I made a new struct

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

    and this is part of my header template

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

    I did the execute template part with the header first with the respective header interface and then another execute template with its respective interface. Also i had to remove the {{template "header"}} part from index.html. The result Looks perfect now and is working the way I want it to.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助