samadadi
samadadi

Reputation: 3370

How to access struct field value in a map of that struct with a specific key

I have "FormError" struct. I pass this struct to my template. So how to access InputError struct field value with specific key in the template?

type InputError struct {
    Val string
    Has bool
}

type FormError struct {
    Errs map[string]InputError
}

This doesn't work.

<input name="Name" type="text" value="{{index .Errs.Val `Name`}}">

Upvotes: 3

Views: 5252

Answers (2)

Marc
Marc

Reputation: 21035

Errs.Val isn't valid, you need to separate the lookup and field access:

{{ $myval := index .Errs "key" }} {{ $myval.Val }}

Or if you only need to use the value once:

{{ (index .Errs "key").Val }}

Upvotes: 4

Thundercat
Thundercat

Reputation: 120941

Use {{.Errs.Name.Val}}. There's no need to use index.

playground example

Upvotes: 2

Related Questions