dtdfj08626 2014-11-24 12:34 采纳率: 0%
浏览 31
已采纳

直接从Revel模板引擎提取模型

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条回答 默认 最新

  • doubo4336 2014-11-24 12:53
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助