Aula 03 - Golang para Web - HTML templates
Se gostarem do conteúdo dêem um joinha 👍 na página do Código Fluente no
Facebook
Link do código fluente no Pinterest
Meus links de afiliados:
Código da aula: Github
HTML templates
Agora vamos escrever
HTMLs em nossas respostas
ao invés de imprimir simples strings como fizemos na aula anterior.
Os
templates nos permitem inserir valores da nossa aplicação para o
HTML resultante.
Crie uma pasta chamada
templates.
Dentro dela crie um arquivo chamado
index.html, outro chamado
about.html e um terceiro chamado
contact.html.
Coloque esse
HTML básico neles.
templates/index.html
<html>
<head>
<title>Página principal</title>
</head>
<body>
<h1>Um texto em H1 da página Index</h1>
</body>
</html>
templates/about.html
<html>
<head>
<title>Sobre</title>
</head>
<body>
<h1>Um texto em H1 da página Sobre</h1>
</body>
</html>
templates/contact.html
<html>
<head>
<title>Contato</title>
</head>
<body>
<h1>Um texto em H1 da página Contato</h1>
</body>
</html>
Vamos voltar para ao
main.go e importar o pacote
html/template em nosso projeto.
Precisamos que nossos
templates sejam acessíveis a partir de nossas rotas.
Para isso, crie um objeto global chamado
templates.
Ele será usado dentro de cada
handler, para chamar o
ExecuteTemplate do objeto
templates e linkar com o
html correto para renderizar.
O que tá em
laranja são os códigos novos, o que tá em
vermelho é o que vai sair. Tá inclusive comentado.
O que vamos fazer no código:
package main
import(
//"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"html/template"
)
var templates *template.Template
func main(){
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/contact", contactHandler).Methods("GET")
r.HandleFunc("/about", aboutHandler).Methods("GET")
r.HandleFunc("/", indexHandler).Methods("GET")
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8000", nil))
}
//request index page handle
func indexHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "index.html", nil)
//fmt.Fprint(w, "This is the index page!")
}
//request contact page handle
func contactHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "contact.html", nil)
//fmt.Fprint(w, "This is the contact page!")
}
//request about page handle
func aboutHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "about.html", nil)
//fmt.Fprint(w, "This is the about page!")
}
Acesse:
Modificando os HTMLs (Bind)
Modifique os arquivos abaixo para a gente usar o
bind e pegar uma string passada pelo
ExecuteTemplate do objeto
templates para o
html.
templates/index.html
<html>
<head>
<title>Página principal</title>
</head>
<body>
<h1>{{ . }}</h1>
</body>
</html>
templates/about.html
<html>
<head>
<title>Sobre</title>
</head>
<body>
<h1>{{ . }}</h1>
</body>
</html>
templates/contact.html
<html>
<head>
<title>Contato</title>
</head>
<body>
<h1>{{ . }}</h1>
</body>
</html>
Vamos modificar o
main.go para passar uma string para ser renderizada nos
HTMLs, fazendo um
bind.
package main
import(
"log"
"net/http"
"github.com/gorilla/mux"
"html/template"
)
var templates *template.Template
func main(){
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/contact", contactHandler).Methods("GET")
r.HandleFunc("/about", aboutHandler).Methods("GET")
r.HandleFunc("/", indexHandler).Methods("GET")
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8000", nil))
}
//request index page handle
func indexHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "index.html", "This is the index page!")
}
//request contact page handle
func contactHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "contact.html", "This is the contact page!")
}
//request about page handle
func aboutHandler(w http.ResponseWriter, r *http.Request){
templates.ExecuteTemplate(w, "about.html", "This is the about page!")
}
Acesse novamente para conferir:
Ficamos por aqui!
Código da aula: Github
Se gostarem do conteúdo dêem um joinha 👍 na página do Código Fluente no
Facebook
Link do código fluente no Pinterest
Novamente deixo meus link de afiliados:
Obrigado, até a próxima e bons estudos. ;)