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("{{.}}
<script>{{.}}</script>
{{.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.