Golang模板:如何在变量中定义数组?

huangapple go评论92阅读模式
英文:

Golang templates : how to define array in a variable?

问题

在Go模板中定义数组变量的正确语法是什么?(这里是一个HTML模板)。以下是我尝试的方式:

{{define "template"}}
    {{ $x:=[]int{0,1,2} }}{{$x.0}}
{{end}}

错误日志显示:命令中出现意外的“[”

谢谢。

英文:

What would be the correct syntax to define an array variable inside a go template ? (here a HTML template). Here's what I tried :

{{define "template"}}
	{{ $x:=[]int{0,1,2} }}{{$x[0]}}
{{end}}

The error log says : unexpected "[" in command

Thanks.

答案1

得分: 19

你想要实现的功能没有内置的方法。可以查看参数以了解如何使用参数和流水线。

但是,你可以很容易地定义自己的函数来实现你的目标:

package main

import (
	"html/template"
	"os"
)

func main() {
tmpl := `
{{ $slice := mkSlice "a" 5 "b" }}
{{ range $slice }}
     {{ . }}
{{ end }}
`
	funcMap := map[string]interface{}{"mkSlice": mkSlice}
	t := template.New("demo").Funcs(template.FuncMap(funcMap))
	template.Must(t.Parse(tmpl))
	t.ExecuteTemplate(os.Stdout, "demo", nil)
}

func mkSlice(args ...interface{}) []interface{} {
	return args
}

Playground.

英文:

there is no built-in way to do what you want to achieve. See the arguments on what you can do with the arguments and the pipeline.

But you could easily define your own function to achieve your goal:

package main

import (
	"html/template"
	"os"
)

func main() {
tmpl := `
{{ $slice := mkSlice "a" 5 "b" }}
{{ range $slice }}
     {{ . }}
{{ end }}
`
	funcMap := map[string]interface{}{"mkSlice": mkSlice}
	t := template.New("demo").Funcs(template.FuncMap(funcMap))
	template.Must(t.Parse(tmpl))
	t.ExecuteTemplate(os.Stdout, "demo", nil)
}

func mkSlice(args ...interface{}) []interface{} {
	return args
}

Playground.

答案2

得分: 8

你可以使用sprig库来帮助你(我在helm模板中使用它,helm模板是go模板,但helm内置了sprig)。

$myList := list 0 1 2
$new = append $myList 3

参考Sprig Lists

英文:

You can use the sprig library to help here (I'm using this for helm templates - which are go templates, but helm has sprig builtin)

$myList := list  0 1 2
$new = append $myList 3

From Sprig Lists

huangapple
  • 本文由 发表于 2014年7月29日 17:48:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/25012467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定