How can I build header/base template

I’m doing my first step in go, and had a look at web development (included batteries) before looking for fully matured web framework, I saw this about templates

<h1>{{.PageTitle}}</h1>
<ul>
    {{range .Todos}}
        {{if .Done}}
            <li class="done">{{.Title}}</li>
        {{else}}
            <li>{{.Title}}</li>
        {{end}}
    {{end}}
</ul>

That is loaded from below go code:

package main


import (
    "html/template"
    "net/http"
)



type Todo struct {
    Title string
    Done  bool
}



type TodoPageData struct {
    PageTitle string
    Todos     []Todo
}



func main() {
    tmpl := template.Must(template.ParseFiles("layout.html"))
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        data := TodoPageData{
            PageTitle: "My TODO list",
            Todos: []Todo{
                {Title: "Task 1", Done: false},
                {Title: "Task 2", Done: true},
                {Title: "Task 3", Done: true},
            },
        }
        tmpl.Execute(w, data)
    })
    http.ListenAndServe(":80", nil)
}

My question is:
How can I load 2 templates together, something like base template and index template so that base template remained fixed whatever the page loaded is, index or another.

Something like [header](https://www.php.net/manual/en/function.header.php) in php

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

Or [extending](https://tutorial.djangogirls.org/en/template_extending/) in Django

{% extends 'blog/base.html' %}

{% block content %}
    {% for post in posts %}
        <div class="post">
            <div class="date">
                {{ post.published_date }}
            </div>
            <h2><a href="">{{ post.title }}</a></h2>
            <p>{{ post.text|linebreaksbr }}</p>
        </div>
    {% endfor %}
{% endblock %}

It worked with me by using the above twice, one for layout/header, followed by a one for the index, so my code became:

	tmpl_layout := template.Must(template.ParseFiles("layout.html"))
	tmpl_index := template.Must(template.ParseFiles("index.html"))
		if r.Method != http.MethodPost {
			tmpl_layout.Execute(w, nil)
			tmpl_index.Execute(w, nil)
			return
		}

		tmpl_layout.Execute(w, nil)
		tmpl_index.Execute(w, struct{ Success bool }{true})

And html file are simple without additions, like:

// file: layout,html
 <h1>Welcome</h1>

// file: index.html
 <h1>Nice to see you here</h1>

I tried to do like this but did not work with me, not sure if the code worked with me is the correct one, and the code in the book is old, or what could be the issue!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.