https://github.com/nilorg/ngin
Web framework 包装一些gin功能。
https://github.com/nilorg/ngin
Last synced: about 1 year ago
JSON representation
Web framework 包装一些gin功能。
- Host: GitHub
- URL: https://github.com/nilorg/ngin
- Owner: nilorg
- License: mit
- Created: 2019-03-16T03:42:03.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2022-04-21T03:51:53.000Z (about 4 years ago)
- Last Synced: 2025-02-02T21:30:12.279Z (over 1 year ago)
- Language: Go
- Size: 43.9 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ngin
Web framework 包装一些gin功能。
# 模板结构
```bash
./templates
└── default
├── errors
├── layouts
│ ├── layout.tmpl
│ └── pjax_layout.tmpl
└── pages
├── posts
│ ├── posts.tmpl
└── posts_detail
└── posts_detail.tmpl
```
# 安装插件
```bash
go get -u github.com/gin-contrib/multitemplate
go get -u github.com/nilorg/ngin
```
# 加载模板
```go
// 主题名称
const themeName string = "default"
func loadTemplates(templatesDir string) multitemplate.Render {
r := multitemplate.New()
// 加载布局
layouts, err := filepath.Glob(filepath.Join(templatesDir, themeName, "layouts/*.tmpl"))
if err != nil {
panic(err.Error())
}
// 加载错误页面
errors, err := filepath.Glob(filepath.Join(templatesDir, themeName, "errors/*.tmpl"))
if err != nil {
panic(err.Error())
}
for _, errPage := range errors {
tmplName := fmt.Sprintf("error_%s", filepath.Base(errPage))
r.AddFromFiles(tmplName, errPage)
}
// 页面文件夹
pages, err := ioutil.ReadDir(filepath.Join(templatesDir, themeName, "pages"))
if err != nil {
panic(err.Error())
}
for _, page := range pages {
if !page.IsDir() {
continue
}
for _, layout := range layouts {
pageItems, err := filepath.Glob(filepath.Join(templatesDir, themeName, fmt.Sprintf("pages/%s/*.tmpl", page.Name())))
if err != nil {
panic(err.Error())
}
files := []string{
layout,
}
files = append(files,pageItems...)
tmplName := fmt.Sprintf("%s_pages_%s", filepath.Base(layout), page.Name())
fmt.Println(tmplName, files)
r.AddFromFiles(tmplName, files...)
}
}
// 加载单页面
singles, err := filepath.Glob(filepath.Join(templatesDir, themeName, "singles/*.tmpl"))
if err != nil {
panic(err)
}
for _, singlePage := range singles {
tmplName := fmt.Sprintf("singles_%s", filepath.Base(singlePage))
r.AddFromFiles(tmplName, singlePage)
}
return r
}
```
# 使用模板
```go
engine := gin.Default()
engine.HTMLRender = loadTemplates("./templates")
```
# 给路由配置模板
```go
import ngin "github.com/nilorg/ngin"
engine.GET("/detail", ngin.WebControllerFunc(func(ctx *ngin.WebContext) {
ctx.RenderPage(gin.H{
"title":"标题",
})
}, ngin.PageName("posts_detail")))
```