How to calculate something in html/template

佐手、 提交于 2020-01-25 07:31:12

问题


How can you calculate something inside a html template of go?

For example:

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

Were the . is a map.
The code {{ $length -1 }} is not working, is there a way to achieve this?


回答1:


You can't. Templates are not a scripting language. By design philosophy, complex logic should be outside of templates.

Either pass the calculated result as a parameter (preferred / easiest), or register custom functions which you can call during template execution, pass values to them and which may perform calculations and return any values (e.g. return param - 1).

For examples of registering and using custom functions, see:

Golang templates (and passing funcs to template)

How do I access object field by variable in template?

Iterate Go map get index.




回答2:


You can use a FuncMap like this. Once you define a function within a funcmap, you can use it in the HTML. In your case you could define a MapLength function or something similar that calculates the length of a given map and returns it for you. You can then call it in the template a bit like this:

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



回答3:


The other answers are correct, you can't do it in the template themselves. However, here's a working example of how to use 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)
}

Playground: https://play.golang.org/p/YNchaHc5Spz



来源:https://stackoverflow.com/questions/52814840/how-to-calculate-something-in-html-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!