Go Templates - Loading from an object store / Database

645 views Asked by At

I'm rebuilding an app that supports customer specific templating (themes) from node.js to Go.

I'm currently using render to render my template files but what I actually need to do access templates that are stored in an object store such as Cloudfiles.

In node.js I've done this with express and I'm overriding the render() method but I've not been able to figure out how to do this in Go.

I essentially need to do something like this:

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})
}

I can dynamically include sub-templates by doing something like this if needed: http://play.golang.org/p/7BCPHdKRi2 but it doesn't seem like a great way if I'm honest.

I've searched for a solution to this but keep hitting road blocks. Any advice / assistance would be great.

Edit:

In essence, I'm asking the following:

  1. How can I load a specific template from a datastore on a per-request basis.
  2. How can I then send that as a response to the client
1

There are 1 answers

0
Jiang YD On BEST ANSWER

How can I load a specific template from a datastore on a per-request basis.

//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)

How can I then send that as a response to the client

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