如何在 html/template 中计算某些东西
How to calculate something in html/template
如何计算 html go 模板中的内容?
例如:
{{ $length := len . }}
<p>The last index of this map is: {{ $length -1 }} </p>
如果 .
是地图。
代码 {{ $length -1 }}
不起作用,有什么办法可以实现吗?
您可以使用像 this 这样的 FuncMap。一旦在 funcmap 中定义了一个函数,就可以在 HTML 中使用它。在你的情况下,你可以定义一个 MapLength 函数或类似的东西来计算给定地图的长度,并为你 returns 它。然后您可以像这样在模板中调用它:
<p>The last index of this map is: {{ .MapLength . }} </p>
你不能。模板不是脚本语言。按照设计理念,复杂的逻辑应该在模板之外。
要么将计算结果作为参数传递(首选/最简单),要么注册您可以在模板执行期间调用的自定义函数,将值传递给它们并且可以执行计算和 return 任何值(例如return param - 1
).
注册和使用自定义函数的例子见:
.
其他答案都是正确的,你不能自己在模板中做。但是,这是一个如何使用 Funcs
:
的工作示例
package main
import (
"fmt"
"html/template"
"os"
)
type MyMap map[string]string
func LastMapIndex(args ...interface{}) string {
if m, ok := args[0].(MyMap); ok && len(args) == 1 {
return fmt.Sprintf("%d", len(m) - 1)
}
return ""
}
func main() {
myMap := MyMap{}
myMap["foo"] = "bar"
t := template.New("template test")
t = t.Funcs(template.FuncMap{"LastMapIndex": LastMapIndex})
t = template.Must(t.Parse("Last map index: {{.|LastMapIndex}}\n"))
t.Execute(os.Stdout, myMap)
}
如何计算 html go 模板中的内容?
例如:
{{ $length := len . }}
<p>The last index of this map is: {{ $length -1 }} </p>
如果 .
是地图。
代码 {{ $length -1 }}
不起作用,有什么办法可以实现吗?
您可以使用像 this 这样的 FuncMap。一旦在 funcmap 中定义了一个函数,就可以在 HTML 中使用它。在你的情况下,你可以定义一个 MapLength 函数或类似的东西来计算给定地图的长度,并为你 returns 它。然后您可以像这样在模板中调用它:
<p>The last index of this map is: {{ .MapLength . }} </p>
你不能。模板不是脚本语言。按照设计理念,复杂的逻辑应该在模板之外。
要么将计算结果作为参数传递(首选/最简单),要么注册您可以在模板执行期间调用的自定义函数,将值传递给它们并且可以执行计算和 return 任何值(例如return param - 1
).
注册和使用自定义函数的例子见:
其他答案都是正确的,你不能自己在模板中做。但是,这是一个如何使用 Funcs
:
package main
import (
"fmt"
"html/template"
"os"
)
type MyMap map[string]string
func LastMapIndex(args ...interface{}) string {
if m, ok := args[0].(MyMap); ok && len(args) == 1 {
return fmt.Sprintf("%d", len(m) - 1)
}
return ""
}
func main() {
myMap := MyMap{}
myMap["foo"] = "bar"
t := template.New("template test")
t = t.Funcs(template.FuncMap{"LastMapIndex": LastMapIndex})
t = template.Must(t.Parse("Last map index: {{.|LastMapIndex}}\n"))
t.Execute(os.Stdout, myMap)
}