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

    {{range .Todos}}
        {{if .Done}}
            <li class="done">{{.Title}}</li>

That is loaded from below go code:

package main

import (

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]( in php

/* This will give an error. Note the output
 * above, which is before the header() call */

Or [extending]( in Django

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

{% block content %}
    {% for post in posts %}
        <div class="post">
            <div class="date">
                {{ post.published_date }}
            <h2><a href="">{{ post.title }}</a></h2>
            <p>{{ post.text|linebreaksbr }}</p>
    {% 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)

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

And html file are simple without additions, like:

// file: layout,html

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