Gin框架下使用模板引入其他模版(可重复使用的模板)

3161人浏览 2021-02-22

   我们的应用程序将使用其模板显示一个网页。但是,将有几个部分,例如页眉,菜单,侧边栏和页脚,这将在所有页面中通用。Go允许我们创建可重用的模板片段,这些片段可以导入其他模板中。页眉和页脚将是将在所有模板中重复使用的通用部分。我们还将在其自己的模板文件中创建菜单,该菜单文件将由标题模板使用。最后,我们将为索引页面创建模板,该模板将导入页眉和页脚。所有模板文件都将放置在templates项目目录内的目录中。

文件结构:

1.创建hearder模板文件。

<!--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-->

2.创建footer模板文件。

<!--footer.html-->

</body>
</html>

3.在index.html中使用hearder和footer模板。

<!--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" .}}

4.创建监听路由,渲染模板。

// 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()

}

 

 

 

推荐文章

GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名
2021-02-23
KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
搜索文章