繁体   English   中英

如何计算html / template中的内容

[英]How to calculate something in html/template

您如何计算go的html模板中的内容?

例如:

{{ $length := len . }}
<p>The last index of this map is: {{ $length -1 }} </p>

. 是一张地图。
代码{{ $length -1 }}无法正常工作,有没有办法实现?

你不能 模板不是脚本语言。 根据设计哲学,复杂的逻辑应该在模板之外。

要么将计算结果作为参数传递(首选/最简单),要么注册可在模板执行期间调用的自定义函数,将值传递给它们,并可以执行计算并返回任何值(例如return param - 1 )。

有关注册和使用定制功能的示例,请参见:

Golang模板(并将函子传递给模板)

如何通过模板中的变量访问对象字段?

迭代Go map获取索引

您可以像这样使用FuncMap。 在funcmap中定义函数后,就可以在HTML中使用它。 在您的情况下,您可以定义MapLength函数或类似的函数来计算给定地图的长度并将其返回给您。 然后,您可以在模板中调用它,如下所示:

<p>The last index of this map is: {{ .MapLength . }} </p>

其他答案是正确的,您不能在模板本身中完成。 但是,这是一个如何使用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)
}

游乐场: https : //play.golang.org/p/YNchaHc5Spz

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM