go - 如何为具有公共部分的多个模型渲染模板
问题描述
我的 golang 项目中有许多带有 CRUD 视图的模型,我想用常见的页眉和页脚渲染这些模型,但不知道该怎么做。我看到的例子太简单了。
假设我有一个这样的模板结构:
templates
- layouts
- header.tmpl
- footer.tmpl
- users
- index.tmpl
- new.tmpl
- edit.tmpl
- show.tmpl
- venues
- index.tmpl
- new.tmpl
- edit.tmpl
- show.tmpl
如何使用通用页眉和页脚为指定模型呈现这些模板?
解决方案
只是一个准系统解决方案如下:
package main
import (
"fmt"
"os"
"text/template"
)
func main() {
//read in one go the header, footer and all your other tmpls.
//append to that slice every time the relevant content that you want rendered.
alltmpls := []string{"./layouts/header.tmpl", "./layouts/footer.tmpl", "./users/index.tmpl"}
templates, err := template.ParseFiles(alltmpls...)
t := templates.Lookup("header.tmpl")
t.ExecuteTemplate(os.Stdout, "header", nil)
t = templates.Lookup("index.tmpl")
t.ExecuteTemplate(os.Stdout, "index", nil)
t = templates.Lookup("footer.tmpl")
t.ExecuteTemplate(os.Stdout, "footer", nil)
}
实际上,您可能需要一个返回适当文件切片的函数来填充 alltmpls 变量。它应该扫描您的目录并从那里获取所有文件以传递给 ParseFiles() 然后继续为每个模板调用 Lookup 和 ExecuteTemplate 步骤。
进一步考虑这个想法,我将创建一个新类型,该类型将嵌入一个模板(或模板片段),由页眉和页脚进行注释。
type hftemplate struct {
template.Template
header, footer *template.Template
}
func (h *hftemplate) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
h.header.ExecuteTemplate(wr, "header", nil)
err := h.ExecuteTemplate(wr, name, data)
h.footer.ExecuteTemplate(wr, "footer", nil)
return err
}
当然,您可以将该结构嵌入转换为 []Template 的完整字段,以在页眉和页脚之间执行多个 ExecuteTemplates。
推荐阅读
- html - 引导导航栏下拉悬停故障
- node.js - 在 ubuntu 上安装 npm 模块给我一个错误
- libgdx - RayHandler 不适合 Box2D 世界
- caching - 如何刷新 Chrome
- linux - ELF中“.note.ABI-tag”部分的意义是什么?
- android - 如何制作一个从mysql数据库下载动态表单并在填写后上传记录的android应用程序?
- scala - Scala 自定义集合无法在理解中选择正确的映射函数
- javascript - 如何将 xlink:href 绘制到画布上
- c++ - 使用 C++ 在 windows 下获取硬盘驱动器性能
- javascript - 如何在反应中使用json文件进行分页?