登录
首页 >  Golang >  Go问答

如何使用公共部分渲染多个模型的模板

来源:stackoverflow

时间:2024-04-06 19:48:35 325浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何使用公共部分渲染多个模型的模板》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我的 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 的成熟字段,以在页眉和页脚之间执行多个 executetemplate。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何使用公共部分渲染多个模型的模板》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>