Pulling model directly from Revel template engine

174 views Asked by At

I come from Ruby/PHP background, usually I use pull the model from the View directly without controller, for example inside an erb file:

<script>
  var vm = {
    rows: <%= ModelName.rows.to_json %>
  };
  // render vm.rows using client-side javascript
</script>
<div> 
  bla bla
</div>

Is it possible to pull model just like what I did in erb, inside Go/Revel's template?

1

There are 1 answers

2
rob74 On BEST ANSWER

This method of embedding code directly into a template can only be done with interpreted languages such as Ruby and PHP. The Go template packages support some simple instructions (if, else, range etc. - see here for details) but this syntax doesn't come close to a full scripting language - that's probably not intended either. You can call methods such as your to_json method from templates. However (as twotwotwo rightfully pointed out) you may not even need an extra method to convert your data to JSON - if you place it between <script> tags, Go will do the conversion by itself. To customize the conversion, implement the Marshaler interface by providing a MarshalJSON method as described here.

The following example demonstrates outputting a struct directly, in a "script" context and using a method:

package main

import (
    "html/template"
    "log"
    "os"
    "strings"
)

type Greeter struct {
    Repeat     int
    Salutation string
}

func (g Greeter) Perform() string {
    return strings.Repeat(g.Salutation+" ", g.Repeat)
}

func main() {
    sayHi := Greeter{Repeat: 3, Salutation: "Hi!"}
    tmpl, err := template.New("").Parse("{{.}}\n<script>{{.}}</script>\n{{.Perform}}")
    if err != nil {
        log.Fatalf("Parse: %v", err)
    }
    tmpl.Execute(os.Stdout, sayHi)
}

http://play.golang.org/p/f3HShZfd6H

Output:

{3 Hi!}
<script>{"Repeat":3,"Salutation":"Hi!"}</script>
Hi! Hi! Hi!

Revel builds on the Go template packages rather than implementing its own template system, so the above applies to Revel as well.