Oleg Baranov
Oleg Baranov

Reputation: 55

Cast interface{} to type in template

  Templates.ExecuteTemplate(w, "index.html", map[string]interface{} {
        "Games": games})
}

Where games is []map[string]interface{} (mapped result of sql query)

In template:

{{ range $gval := .Games }} 
    {{ how to make something like: $gval.name.(string) }} 
{{end}}

How to cast interface{} value of map to string(or int) in template? In 'go' i can do games[0]["name"].(string)

When i do $gval.name it writes hex string

Upvotes: 2

Views: 9592

Answers (2)

Jerome Ortega
Jerome Ortega

Reputation: 105

I believe accepted answer is no longer necessary. I was just able to use interface{} values without explicitly typecasting it in golang template. I am on go v1.16.

Upvotes: 2

jussius
jussius

Reputation: 3274

I don't think it's possible to do type assertions from a template. You'll have to write your own function and call it from the template. For example:

func ToString(value interface{}) string {
    switch v := value.(type) {
    case string:
        return v
    case int:
        return strconv.Itoa(v)
    // Add whatever other types you need
    default:
        return ""
    }
}

To be able to call the function from template you have to call the Funcs() method on your template:

tpl.Funcs(template.FuncMap{"tostring": ToString})

Now you can do {{$gval.name | tostring}} inside your template

Upvotes: 6

Related Questions