Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse variables outside the range in Go templates?

Tags:

templates

go

I have two structs as below and I need to render the data on a template using the templates pack. I get this error

<.Email>: Email is not a field of struct type Notes.

The issue seems to be that only fields of the range struct seem to be available within the range loop so I'm wondering how I can import fields from outside the range struct (e.g. the Email string).

The behavior is quite unexpected.

type notes struct{
    Note string
    sf string
}

type uis struct{
    notes []Note
    Email string
}

var ui uis

HTML

{{range .notes}}
    {{.Email}} {{.sf}}
    {{end}}

Email {{.Email}}

I've checked the godocs but they seem quite useless.

like image 555
hey Avatar asked Jul 21 '14 11:07

hey


1 Answers

From the documentation:

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

Therefore, you can use this:

{{range .notes}}
    {{$.Email}} {{.sf}}
{{end}}

Email {{.Email}}

(Note the dollar sign inside the range)

Playground link: http://play.golang.org/p/XiQFcGJEyR

Side note: Next time try to provide proper code and a better explanation. As it stands, I think I've answered this, but I cannot be sure. Your code doesn't compile - for example, type names are wrong/mixed with members and you have unexported fields so they cannot be accessed by the templates.

like image 121
Simon Whitehead Avatar answered Nov 11 '22 22:11

Simon Whitehead