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?
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 theMarshaler
interface by providing aMarshalJSON
method as described here.The following example demonstrates outputting a struct directly, in a "script" context and using a method:
http://play.golang.org/p/f3HShZfd6H
Output:
Revel builds on the Go template packages rather than implementing its own template system, so the above applies to Revel as well.