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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘