Golang Web: Head function

Asked

Viewed 78 times

0

Good night,

I’m starting in GO, and I have a question that may seem simple. I am creating a site with GO in Backend, my doubt is I have index.html and main.go created and are working, but in the index I want to add the content of another file called head.html that has all the content of what will be the header of the site, so when create more pages reuse only header function to replicate in all others the head, someone knows how to do a function for this in Golang?

  • Depends, which lib is using the native HTTP lib? or is using a framework?

1 answer

1


Whereas you’re using the html/template, you can wow the {{template "nome do template"}} for it to be inserted.

All "commands" can be viewed at https://golang.org/pkg/text/template/:

{{template "name"}}

    The template with the specified name is executed with nil data.

{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.

So considering you have two files, you could do:

header.html

{{define "header"}}
<header>
    Este é o cabeçalho de {{.Fulano}}
</header>
{{end}}

index.html

{{define "index"}}
{{template "header" .}}
<body>
    Este é o corpo de {{.Fulano}}
</body>
{{end}}

No Golang could use:

package main

import (
    "html/template"
    "os"
)

func main() {
    t, err := template.ParseGlob(`path\to\*.html`)
    if err != nil {
        panic(err)
    }

    type Exemplo struct {
        Fulano string
    }

    if err = t.ExecuteTemplate(os.Stdout, "index", &Exemplo{Fulano: "Sicrano"}); err != nil {
        panic(err)
    }

}

That would result in:

<header>
    Este é o cabeçalho de Sicrano
</header>

<body>
    Este é o corpo de Sicrano
</body>

Note that the {{define}} to name each "file". In the second case, the index.html, is used the {{template "header" .}} and this is intended to inject the content that has been defined using {{define "header"}}.


Finally, to inject one another use the {{define "nome}} and then use the {{template "nome"}} to insert the content. In the above case, it is used {{template "nome" .}} (note the . at the end) to allow the "header" to have access to the Exemplo and read the Fulano.

  • That’s exactly what I was needing, although it seemed easy I wasn’t finding this explanation on the web, thank you very much. Worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.