您的位置 首页 编程知识

使用Packr内嵌模板时,如何在Gin框架中正确渲染HTML页面?

packr gin 模板输出 在 gin 中,通常使用 router.loadhtmlglob(“…

packr gin 模板输出

在 gin 中,通常使用 router.loadhtmlglob(“templates/*”) 加载静态 html 文件。然而,当使用 packr 将静态文件作为资源文件内嵌时,则需要采用不同的方法。

packr 可以通过 findstring 方法获取静态文件的字符串内容,但无法直接与 gin 中的变量输出配合使用。是使用 html/template 解析 packr 中的模板文件:

初始化模板

首先,使用 findstring 查找模板文件的内容,然后创建并解析模板:

立即学习“”;

func inittemplates() *template.template {     box := packr.newbox("./templates")     t := template.new("")      tmpl := t.new("index.html")     data, _ := box.findstring("index.html")     tmpl.parse(data)      tmpl = t.new("admin/index.html")     data, _ = box.findstring("admin/index.html")     tmpl.parse(data)     return t }
登录后复制

设置 gin 模板引擎

接下来,使用 sethtmltemplate 方法设置刚刚创建的模板:

func main() {     r := gin.Default()     r.SetHTMLTemplate(initTemplates())     r.GET("/", func(c *gin.Context) {         c.HTML(200, "index.html", nil)     })     r.Run() }
登录后复制

这样一来,就可以使用 gin 的 html 输出功能,将 packr 内嵌的模板文件渲染为带变量的页面。

以上就是使用Packr内嵌模板时,如何在Gin框架中正确渲染HTML页面?的详细内容,更多请关注php中文网其它相关文章!

本文来自网络,不代表四平甲倪网络网站制作专家立场,转载请注明出处:http://www.elephantgpt.cn/7409.html

作者: nijia

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

联系我们

联系我们

18844404989

在线咨询: QQ交谈

邮箱: 641522856@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部