Search code examples
gogo-html-template

How to execute multiple templates in a single webpage using different interfaces in 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?


Solution

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