gin框架03--html 模板渲染

  • 介绍
  • 案例
    • 加载 templates 目录下的文件
    • 加载多个子目录下的文件
    • 自定义模板渲染器
    • 自定义模板功能
  • 说明

介绍

gin支持加载HTML模板, 然后根据模板参数进行配置并返回相应的数据,本质上就是字符串替换,既可以使用 LoadHTMLGlob() 或者 LoadHTMLFiles() 方法加载模板文件, 也可以使用自定义模板渲染器。

案例

加载 templates 目录下的文件

package mainimport ("github.com/gin-gonic/gin""net/http"
)func main() {r := gin.Default()r.LoadHTMLGlob("templates/*")r.GET("/index", func(c *gin.Context) {c.HTML(http.StatusOK, "index.tmpl", gin.H{"title": "Main website",})})r.Run(":8080")
}

templates/index.tmpl

<html><h1>{{ .title }}</h1>
</html>

测试

目录结构:
├── go.mod
├── go.sum
├── main.go
└── templates└── index.tmpl
输出:
http://127.0.0.1:8080/index
Main website

加载多个子目录下的文件

package mainimport ("github.com/gin-gonic/gin""net/http"
)func main() {r := gin.Default()r.LoadHTMLGlob("templates/**/*")r.GET("/posts/index", func(c *gin.Context) {c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{"title": "Posts",})})r.GET("/users/index", func(c *gin.Context) {c.HTML(http.StatusOK, "users/index.tmpl", gin.H{"title": "Users",})})r.Run(":8080")
}

templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

templates/users/index.tmpl

{{ define "users/index.tmpl" }}
<html><h1>{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

测试

目录结构:
.
├── go.mod
├── go.sum
├── main.go
└── templates├── posts│   └── index.tmpl└── users└── index.tmpl
输出:
http://127.0.0.1:8080/posts/index
Posts
Using posts/index.tmplhttp://127.0.0.1:8080/users/index
Users
Using users/index.tmpl

自定义模板渲染器

我们可以使用自定义的 html 模板渲染, 如下使用 template.ParseFiles 函数,那么第一个模板为 posts.tmpl, 第二个模板为 users.tmpl
vim main.go

package mainimport ("github.com/gin-gonic/gin""html/template""net/http"
)func main() {router := gin.Default()html := template.Must(template.ParseFiles("templates/posts.tmpl","templates/users.tmpl"))router.SetHTMLTemplate(html)router.GET("/posts", func(c *gin.Context) {c.HTML(http.StatusOK, "posts.tmpl", gin.H{"title": "posts.tmpl",})})router.GET("/users", func(c *gin.Context) {c.HTML(http.StatusOK, "users.tmpl", gin.H{"title": "users.tmpl",})})router.Run(":8080")
}

vim posts.tmpl

{{ define "posts.tmpl" }}
<html><h1>{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

vim users.tmpl

{{ define "users.tmpl" }}
<html><h1>{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

测试

目录结构:
.
├── go.mod
├── go.sum
├── main.go
└── templates├── posts.tmpl└── users.tmpl
输出:
http://127.0.0.1:8080/users
users.tmpl
Using users/index.tmplhttp://127.0.0.1:8080/posts
posts.tmpl
Using posts/index.tmpl

自定义模板功能

默认分隔符为 {{ }}, 我们也可以使用自定义分隔 {[{ }]}, 只需要通过 r.Delims 即可实现

 r := gin.Default()r.Delims("{[{", "}]}")r.LoadHTMLGlob("/path/to/templates")

main.go

package mainimport ("fmt""html/template""net/http""time""github.com/gin-gonic/gin"
)func formatAsDate(t time.Time) string {year, month, day := t.Date()return fmt.Sprintf("%d%02d/%02d", year, month, day)
}func main() {router := gin.Default()router.Delims("{[{", "}]}")router.SetFuncMap(template.FuncMap{"formatAsDate": formatAsDate,})router.LoadHTMLFiles("./testdata/raw.tmpl")router.GET("/raw", func(c *gin.Context) {c.HTML(http.StatusOK, "raw.tmpl", gin.H{"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),})})router.Run(":8080")
}

testdata/raw.tmpl

Date: {[{.now | formatAsDate}]}

测试

目录结构:
.
├── go.mod
├── go.sum
├── main.go
└── testdata└── raw.tmpl
输出:
http://127.0.0.1:8080/raw
Date: 201707/01

说明

软件环境:
ubuntu 20.04.1 LTS Desktop
go version go1.17.6 linux/amd64
参考文档:
gin官方文档–HTML 渲染
gin中文文档–html 渲染
golang自定义模板示例
gin系列-模板引擎

gin框架03--html 模板渲染相关推荐

  1. png文件头_Golang GinWeb框架7静态文件/模板渲染

    简介 本文接着上文(Golang GinWeb框架6-绑定请求字符串/URI/请求头/复选框/表单类型)继续探索GinWeb框架 静态文件服务 package mainimport ( "g ...

  2. Gin 框架学习笔记(03)— 输出响应与渲染

    在 Gin 框架中,对 HTTP 请求可以很方便有多种不同形式的响应.比如响应为 JSON . XML 或者是 HTML 等. ​ Context 的以下方法在 Gin 框架中把内容序列化为不同类型写 ...

  3. Go gin静态文件的使用、自定义模板渲染器

    Go gin静态文件的使用 一.指定静态文件路径 engine.Static("/static", "static") 第一个参数是url,第二个参数是url对 ...

  4. flask mysql项目模板渲染_Flask框架模板渲染操作简单示例

    本文实例讲述了Flask框架模板渲染操作.分享给大家供大家参考,具体如下: from flask import render_template from flask import Flask from ...

  5. Gin框架从入门到上手学习指南

    推荐一个Golang的学习站:Go中文学习文档 (halfiisland.com) Gin 官方文档:Gin Web Framework (gin-gonic.com) 仓库地址:gin-gonic/ ...

  6. [golang gin框架] 27.Gin 商城项目-购物车

    1.先来看一个问题 购物车数据保持到哪里? 1.购物车数据保存在本地 (cookie或者 redis缓存中),下面统一保存到cookie中,保存到redis中和cookie中逻辑步骤其实都是一样的 2 ...

  7. 【Gin框架】框架入门

    阅读目录 一.Gin 介绍 二.Gin 环境搭建 三.golang 程序的热加载 四.Gin 框架中的路由 4.1.路由概述 4.2.简单的路由配置 4.3.c.String().c.JSON().c ...

  8. golang中的gin框架学习

    gin框架中常用方法 gin.H{ } 有这么一行c.JSON(200, gin.H{"message": "use get method"}) 这其中有一个g ...

  9. 详细讲解go web框架之gin框架源码解析记录及思路流程和理解

    开篇 首先gin 框架是在 官方提供的net/http标准包进行的相应封装. 那么要想理解gin框架, 就要先懂一些 net/http标准包 的相关知识. 可以参考中文的 文档: https://st ...

  10. Golang源码学习----gin框架简单阅读

    一.热加载go get github.com/pilu/fresh快速编译,省去了每次手动go run二.gin特点轻量级.运行速度快,性能.高效擅长API接口的高并发,项目规模不大,业务简单三.En ...

最新文章

  1. SqlServer2000日志文件过大问题处理
  2. RHEL 6 关闭ThinkPad 触摸板
  3. JAVA访问控制符(写给初学者的)
  4. “举报”阿里巴巴 Arthas,大幅降低 OOM Trouble shooting 门槛
  5. [POJ2976] Dropping tests
  6. java布局管理怎么有图片_java-用于背景图像和文本的布局管理器
  7. a标签的href与onclick中使用js的区别
  8. Bert在CV领域的应用
  9. linux的基础知识——TCP握手
  10. Java基础学习总结(141)——Cron 表达式使用再总结
  11. matlab2c使用c++实现matlab函数系列教程-sort函数
  12. 去除datatable列中重复的值
  13. (转)“版本上线延时”问题与对策的探讨
  14. GoEasy使用详解
  15. Win10网卡驱动突然消失
  16. aruba交换机配置命令_ArubaOS交换机日常配置指导
  17. android蓝牙配对 自动联接,如何实现android蓝牙开发 自动配对连接,并不弹出提示框...
  18. c++#学生平均成绩,学号排序
  19. 众所周知的广告屏蔽神器uBlock/Adguard,为啥你装上后和没装一样?
  20. OPCODES学习网址

热门文章

  1. python+appium自动化测试-元素等待
  2. python get hist data_[宜配屋]听图阁
  3. 微软hotmail服务器,Hotmail已死,微软又推了Gmail一把
  4. android识别人脸并放贴纸,超简单集成HMS ML Kit 人脸检测实现可爱贴纸
  5. 走出笔记本电池维护八大误区
  6. 计算机病毒有什么类型,计算机病毒有哪些类型? - 问答库
  7. 利用python实现排序,并标上序号
  8. Memory read error at 0xF8007080. AHB AP transaction error, DAP status f0000021
  9. Qt生成不重复的随机数
  10. codeforces 1148E- Earth Wind and Fire