欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 名人名企 > niuhe插件, 在 go 中渲染网页内容

niuhe插件, 在 go 中渲染网页内容

2025/5/16 16:42:56 来源:https://blog.csdn.net/maiz_shi/article/details/146958404  浏览:    关键词:niuhe插件, 在 go 中渲染网页内容

思路

niuhe 插件生成的 go 代码是基于 github.com/ma-guo/niuhe 库进行组织管理的, niuhe 库 是对 go gin 库的一个封装,因此要显示网页, 可通过给 gin.Engine 指定 HTMLRender 来实现。

实现

HTMLRender 我们使用 gitee.com/cnmade/pongo2gin 实现

1. main.go 中指定 HTMLRender

RegisterModules 中指定 HTMLRender

func (baseBoot) RegisterModules(svr *niuhe.Server) {svr.RegisterModule(apiViews.GetModule())svr.GetGinEngine().HTMLRender = pongo2gin.Default() // pongo2gin 在下面定义svr.GetGinEngine().Static("/static", "static") // 指定静态路径映射位置
}

示例代码: https://github.com/ma-guo/niuhe-mdbook/blob/main/src/demo/main.go

2. 在代码中引入 .html

在 all.niuhe 中定义 api GET('网页示例', '/api/hellow/web/'), 在 hellow.go 文件夹 内实现以下代码:

// 网页示例
func (v *Hellow) Web_GET(c *niuhe.Context) {// 在此实现具体方法, 需要自行处理请求参数和返回数据// 这里会在 templates 文件夹下查找 index.html 文件c.HTML(http.StatusOK, "index.html", pongo2.Context{ "title":   "网页 title","message": "这是一条消息",})
}

参考代码: https://github.com/ma-guo/niuhe-mdbook/blob/main/src/demo/app/api/views/hellow_views.go

这里 index.html 代码为:

<!DOCTYPE html>
<html><head><title>{{title}}</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css"></head><body><div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">{{message}}</h4></div></div></body>
</html>

参考代码: https://github.com/ma-guo/niuhe-mdbook/blob/main/templates/index.html

运行代码并访问 API 即实现了 .html 的渲染。效果如下
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词