How to calculate something in html/template
Asked Answered
L

3

0

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?

Led answered 15/10, 2018 at 10:38 Comment(0)
P
2

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.

Postmillennialism answered 15/10, 2018 at 10:53 Comment(1)
Thanks, I saw that you can use some functions like len() and others inside the html template. Hoped there would be like a calculate function.Led
P
2

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

Primacy answered 15/10, 2018 at 10:56 Comment(0)
P
1

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>
Plaything answered 15/10, 2018 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.