Golang中"text/template"模板的减法运算实现
Golang中"text/template"模板的减法运算实现 你好,我无法在 if 条件中进行减法运算,这正常吗?
我的代码:
{{$len := len .Members}}
{{if gt $len 1}}
{{range $key2, $value2 := .Members}}
{{$value2}}
{{if lt $key2 $len-1}}
|
{{end}}
{{end}}
{{end}}
有什么想法吗? 谢谢
3 回复
通常你可以修改你的模板来使表达式变得不必要:
{{range $key2, $value2 := .Members}}
{{- if gt $key2 0}}|{{end}}{{$value2}}
{{- end}}
更多关于Golang中"text/template"模板的减法运算实现的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
然而,针对您关于减法的问题:您说得对,在 Go 模板中不能使用像 +、- 这样的中缀运算符。这就是为什么小于检查是 lt left right。您可以像这样编写自己的 sub 函数:
func sub(a, b int) int { return a - b}
// 然后在初始化模板的地方,像这样注册您的 sub 函数:
tmpl := template.New("")/* ... */.Funcs(template.FuncMap{"sub": sub})/* ... */.Execute(...)
在Go的text/template中,直接在模板表达式中进行算术运算确实有限制。你的代码中$len-1无法直接运算,因为模板引擎不支持这种语法。
正确的实现方式是在模板中预先计算好减法的结果:
{{$len := len .Members}}
{{$lenMinusOne := sub $len 1}}
{{if gt $len 1}}
{{range $key2, $value2 := .Members}}
{{$value2}}
{{if lt $key2 $lenMinusOne}}
|
{{end}}
{{end}}
{{end}}
或者使用更简洁的方式,通过比较索引和长度减1:
{{$len := len .Members}}
{{if gt $len 1}}
{{range $key2, $value2 := .Members}}
{{$value2}}
{{if lt (add $key2 1) $len}}
|
{{end}}
{{end}}
{{end}}
如果你需要在模板中频繁进行数学运算,可以考虑注册自定义函数:
func main() {
funcMap := template.FuncMap{
"sub": func(a, b int) int { return a - b },
"add": func(a, b int) int { return a + b },
}
tmpl := template.New("test").Funcs(funcMap)
// 然后解析和执行模板
}
这样你就可以在模板中使用{{sub $len 1}}进行减法运算了。

