【问题标题】:Go Templates - Loading from an object store / DatabaseGo Templates - 从对象存储/数据库加载
【发布时间】:2015-09-11 05:51:15
【问题描述】:

我正在重建一个支持从 node.js 到 Go 的客户特定模板(主题)的应用程序。

我目前正在使用render 来呈现我的模板文件,但实际上我需要做的是访问存储在 Cloudfiles 等对象存储中的模板。

在 node.js 中,我使用 express 完成了此操作,并且我覆盖了 render() 方法,但我无法弄清楚如何在 Go 中执行此操作。

我基本上需要做这样的事情:

func (c *Controller) MyRouteHandler (rw http.ResponseWriter, req *http.Request) {
    // retrieve the store from the context (assigned in middleware chain)
    store := context.Get(req, "store").(*Store) 

    ... do some stuff like load the entity from the database

    // retrieve the template from the Object store and 
    // create the template instance (template.New("template").Parse(...))
    tpl := c.ObjectStore.LoadTemplate(store, entity.TemplateFile)

    // I know render's .HTML function takes the path to the template 
    // so I'll probably need to show the html a different way
    c.HTML(rw, http.StatusOK, tpl, &PageContext{Title: "My Page", Entity: &entity})
}

如果需要,我可以通过执行以下操作来动态包含子模板:http://play.golang.org/p/7BCPHdKRi2 但老实说,这似乎不是一个好方法。

我一直在寻找解决方案,但一直遇到障碍。任何建议/帮助都会很棒。

编辑:

本质上,我在问以下问题:

  1. 如何根据每个请求从数据存储中加载特定模板。
  2. 我怎样才能将它作为响应发送给客户

【问题讨论】:

  • 所以你真正的问题是找到从 Cloudfiles 加载文本的方法?
  • 不,我可以从 Cloudfiles 加载文件的内容。那一点很容易。它能够使用 Go 将其呈现为模板
  • 对不起,我仍然不知道你真正的问题。
  • 据我所知,默认情况下,Go 的模板要求模板在编译时可用,您需要重新编译才能使模板更改生效。我需要从外部源(如数据库)加载模板并在每次请求之前动态解析它们。
  • 因为你可以在运行时加载 Go 的模板内容,只是为了“即时”读取模板内容并调用 Parse() 函数。

标签: templates go mux gorilla


【解决方案1】:

如何根据每个请求从数据存储中加载特定模板。

//take HTTP for example:
resp, err := http.Get("http://mytemplates.com/template1")
if err != nil {
    // handle error
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
templateString := string(body)

然后我怎样才能将它作为响应发送给客户

tmpl, err := template.New("name").Parse(templateString)
tmpl.Execute(rw, &yourDataModel{})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-31
    • 2017-12-16
    • 2019-03-13
    • 1970-01-01
    • 2013-09-03
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多