普通网友 2015-03-07 17:06
浏览 333
已采纳

Golang。 如何使用html / template包创建循环函数

I'm trying to implement loop as custom function. It takes number of iterations and content between curly brackets, then it should iterate content between brackets n times. Please, see example:

main.go

template.Must(template.ParseFiles("palette.html")).Funcs(template.FuncMap{
        "loop": func(n int, content string) string {
            var r string
            for i := 0; i <= n; i++ {
                r += content
            }
            return r
        },
    }).ExecuteTemplate(rw, index, nil)

index.html

{{define "index"}}
<div class="row -flex palette">
  {{loop 16}}
    <div class="col-2"></div>
  {{end}}
</div>
{{end}}

Output

<div class="row -flex palette">
    <div class="col-2"></div>
    <div class="col-2"></div>
    <div class="col-2"></div>
    <div class="col-2"></div>
    ... 16 times
</div>

Is it possible to implement it? The motivation is that standard functionality of the text/template doesn't allow just to iterate content between curly bracket. Yes we can do it by range action going through "outside" data.

  • 写回答

1条回答 默认 最新

  • duanguilin2007 2015-03-07 18:14
    关注

    You can use range on a function that returns a slice. http://play.golang.org/p/FCuLkEHaZn

    package main
    
    import (
        "html/template"
        "os"
    )
    
    func main() {
        html := `
    <div class="row -flex palette">
      {{range loop 16}}
        <div class="col-2"></div>
      {{end}}
    </div>`
        tmpl := template.Must(template.New("test").Funcs(template.FuncMap{
            "loop": func(n int) []struct{} {
                return make([]struct{}, n)
            },
        }).Parse(html))
        tmpl.Execute(os.Stdout, nil)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面