我们的应用程序将使用其模板显示一个网页。但是,将有几个部分,例如页眉,菜单,侧边栏和页脚,这将在所有页面中通用。Go允许我们创建可重用的模板片段,这些片段可以导入其他模板中。页眉和页脚将是将在所有模板中重复使用的通用部分。我们还将在其自己的模板文件中创建菜单,该菜单文件将由标题模板使用。最后,我们将为索引页面创建模板,该模板将导入页眉和页脚。所有模板文件都将放置在templates项目目录内的目录中。
文件结构:
<!--header.html-->
<!doctype html>
<html>
<head>
<!--Use the `title` variable to set the title of the page-->
<title>{{ .title }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<!--Use bootstrap to make the application look nice-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script async src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
</head>
<body class="container">
<!--Embed the menu.html template at this location-->
<!--footer.html-->
</body>
</html>
<!--index.html-->
<!--Embed the header.html template at this location-->
{{ template "header.html" .}}
<h1>Hello Gin!</h1>
<!--Embed the footer.html template at this location-->
{{ template "footer.html" .}}
// main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
router = gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/", func(c *gin.Context) {
// Call the HTML method of the Context to render a template
c.HTML(
http.StatusOK,
// Use the index.html template
"index.html",
// Pass the data that the page uses (in this case, 'title')
gin.H{
"title": "Home Page",
},
)
})
router.Run()
}