gin 渲染不同目录下的模板(支持多层目录)

本文分享了在Gin框架中进行模板渲染的实际经验,详细介绍了目录结构、布局与内容页面的定义方式,以及如何在Go语言中正确使用gin框架渲染HTML页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一直在学着使用gin,今天试了下gin的模板渲染,一路比较坑。真要吐槽下某度,啥都没有。

参考资料:https://www.bookstack.cn/read/gin-doc/response.md

https://juejin.im/post/5b026a4c6fb9a07aac24c122

https://blog.youkuaiyun.com/moxiaomomo/article/details/51153779

https://blog.youkuaiyun.com/a976134036/article/details/78867297

github源码查看:https://github.com/caogenlaoxian/golang

首先看下我的目录结构:

其中layout放置的是公共html,msg放置的是程序需要的html

layout/header.html文件

(1)任何文件要以{{define "layout/header"}} 开始,最后{{end}}结束,footer.html文件一样要遵循这种方式,

(2)公共头部 define一定不要加文件名的后缀

{{define "layout/header"}}
<!DOCTYPE html>

<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->

<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->

<!--[if !IE]><!--> <html lang="en" class="no-js"> <!--<![endif]-->

<!-- BEGIN HEAD -->

<head>

    <meta charset="utf-8" />

    <title>{{.title}}</title>

    <meta content="width=device-width, initial-scale=1.0" name="viewport" />

    <meta content="" name="description" />

    <meta content="" name="author" />

</head>

<!-- END HEAD -->

<!-- BEGIN BODY -->

<body class="page-header-fixed">

{{end}}

 

msg/index.html

(1)文件要以{{define "msg/index.html"}} 开始,最后{{end}}结束,这里的index可以加文件后缀,index.html

(2)需要通过{{template "layout/head" .}} 最后面有个【点】,它的意思是要把当前页面的变量传递到head.html中。

{{ define "msg/index.html" }}
{{template "layout/header" .}}
<div class="row pull-right" style="margin-bottom: 20px;margin-right: 5px;text-align:right;margin-right: 40px;">
       
          <input type="text" placeholder="请输入名称" id="txt_search"/>
          <button class="" onclick="search()">搜索</button>
 
          <button class="" onclick="adddata()">新增</button>
        </div>
             
        <table class="table table-striped table-hover table-bordered ">
          <thead>
           <th style="text-align: center">ID</th>
           <th style="text-align: center">姓氏</th>
           <th style="text-align: center">名称</th>
           <th style="text-align: center">操作</th>
         </thead>
         
         <tbody id="sortable">
         </tbody>
        </table> <!--分页部分-->
        <div style="margin: 20px 0px 10px 0;">
         <table style="margin: 0 auto;">
             <tr>
                 <td>
                     <div id="pagination" class="pagination"></div>
                 </td>
             </tr>
         </table>
        </div>
		{{range .data}}

			{{.Title}},{{.Content}}



        {{end}}
{{template "layout/footer" .}}
{{end}}

msg.go输出html的代码

c.HTML(http.StatusOK, "msg/index.html", gin.H{
		"title": "测试",
		"data":  lists,
	})

路由设置:

router.LoadHTMLGlob("views/**/*") //渲染模板,一定要/**/*这样代表2层目录

启动服务后,【GIN-debug】显示

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值