当前位置: 首页 > news >正文

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 的渲染。效果如下
在这里插入图片描述

http://www.dtcms.com/a/107008.html

相关文章:

  • 基于React + Antd + Java的OFD文件上传预览实现方案(OFD文件转图片)
  • 删除和关闭 Solana 中的账户和程序
  • Linux网络相关概念和重要知识(4)(序列化和反序列化、TCP协议、会话和守护进程)
  • 基于OpenCV的指纹验证:从原理到实战的深度解析
  • vue3 动态路由
  • 第1章-3 MySQL的逻辑架构
  • 【C++】二叉搜索树
  • 【哈希表】—— 我与C++的不解之缘(二十八)
  • [CISSP] [4] 法律、法规
  • alfred-deepseek开源程序在 Alfred 中与 DeepSeek 聊天
  • [IOI 2000] 回文字串
  • 符号秩检验
  • 跟着尚硅谷学vue-day2
  • 23 种设计模式中的解释器模式
  • C++友元与动态内存
  • 关于存储的笔记
  • go语言:开发一个最简单的用户登录界面
  • 剑指Offer(数据结构与算法面试题精讲)C++版——day3
  • 【数据结构】树、森林与二叉树的转换(含详细图解)
  • TypeScript 泛型与 keyof 约束 | 深入解析
  • 钉钉 + AI 网关给 DeepSeek 办入职
  • Photoshop 2025 Mac中文 Ps图像编辑软件
  • 陈关荣 | 明清江南数学家
  • Cursor助力Java开发(快捷键+配置篇)
  • nginx的反向代理和负载均衡
  • git分布式控制工具详解
  • 深入解析使用Python通过STOMP协议接收ActiveMQ消息
  • 数据库6(数据库指令)
  • Django 使用 matplotlib 遇到 RuntimeError: main thread is not in main loop 解决办法
  • Linux系统程序设计:从入门到高级Day01