This is a creation in Article, where the information may have evolved or changed.
Most of the web has an identical layout. This layout may contain a header or footer, and may even contain a navigation menu. The standard library of Go provides an easy way to create these basic elements, creating the effect of template pages by reusing different pages.
This simple example explains how to accomplish this:
Let's create a simple web with two view, one is main and the other is about. These two view all have the same header and footer.
The code for the header template is as follows:
{{Define "header"}}<! DOCTYPE html>
The code for the footer template is as follows:
{{define ' footer '}} <p class= "Navbar-text navbar-fixed-bottom" >go rocks!</p> <script src= "/http Netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js "></script> </body>
The code for the main template is as follows:
{{define ' main '}} {{Template ' header '.}} <div class= "Content" >
The code for the About template is as follows:
{{define ' about '}} {{Template ' header '.}} <div class= "Content" >
The server code is as follows:
Package Mainimport ( "Html/template", " net/http")//compile templates on Startvar templates=template. Must (template. Parsefiles ("header.html", "footer.html", "main.html", "about.html"))//a page structuretype page struct { Title String}//display the named Templatefunc Display (w http. Responsewriter, Tmpl string, data interface{}) { templates. Executetemplate (W, Tmpl, data)}//the handlers.func MainHandler (w http. Responsewriter, R *http. Request) { display (W, "main", &page{title: "Home"})}func Abouthandler (w http. Responsewriter, R *http. Request) { display (W, "about", &page{title: "About"})}func main { http. Handlefunc ("/", MainHandler) http. Handlefunc ("/about", Abouthandler) //listen on port 8080 http. Listenandserve (": 8080", nil)}
Each template page has a command to define the name of the template. Main and about pages are passed to include headers and footer. "." To name the template from top to bottom. Now, regardless of how the main and about pages are executed, their pages will contain headers and footer.
The results of the two pages are as follows: