Call a function in template while iterating using Range

2,242 views
Skip to first unread message

DEXTER

unread,
Apr 7, 2012, 10:10:43 AM4/7/12
to golang-nuts
Hi
How do I call a function in template while iterating

If I call the function outside the
{{range $index,$val := .Options.Attrs}}
{{$index}}
{{end}}
{{.GetOptionKey 1}} //GetOptionKey is my function

the function executes

But when I try this

{{range $index,$val := .Options.Attrs}}
{{.GetOptionKey $index}} //i want to pass the variable index to
the function
{{end}}

It does parse the template file and does not return any error. The
template block above the range condition is parsed & returned

Dexter

Miki Tebeka

unread,
Apr 7, 2012, 11:09:06 AM4/7/12
to golan...@googlegroups.com
 
How do I call a function in template while iterating
Maybe you can pass the function using http://golang.org/pkg/html/template/#Template.Funcs.
See "Defining Functions" section at http://jan.newmarch.name/golang/template/chapter.html for example.

HTH,
--
Miki
http://go-wise.blogspot.com/

John Asmuth

unread,
Apr 7, 2012, 11:24:01 AM4/7/12
to golan...@googlegroups.com
ranging changes what the dot points at. Try this:

{{if $self := .}}
{{range $index,$val  := .Options.Attrs}}
                     {{$self.GetOptionKey $index}} //i want to pass the variable index to
the function
{{end}}{{end}} 

DEXTER

unread,
Apr 8, 2012, 9:31:20 AM4/8/12
to golang-nuts
Hi,
Thanks this worked.

{if $self := .}}
{{range $index,$val := .Options.Attrs}}
{{$k := $self.Options.GetOptionKey $index}}
<div id="{{$k}}">{{$k}}</div>
{{end}}
{{end}}

Now I have another problem
Can I call function that returns multiple values from a template
{if $self := .}}
{{range $index,$val := .Options.Attrs}}
{{$k,$v := $self.Options.GetOptionKey $index}}
<div id="{{$k}}">{{$v}}</div>
{{end}}
{{end}}

It only works when the function returns 1 value

Kyle Lemons

unread,
Apr 8, 2012, 4:48:50 PM4/8/12
to DEXTER, golang-nuts
On Sat, Apr 7, 2012 at 7:10 AM, DEXTER <djc...@gmail.com> wrote:
Hi
How do I call a function in template while iterating

If I call the function outside the
{{range $index,$val  := .Options.Attrs}}
                    {{$index}}
{{end}}
{{.GetOptionKey 1}} //GetOptionKey is my function

 the function executes

But when I try this

{{range $index,$val  := .Options.Attrs}}
                    {{.GetOptionKey $index}} //i want to pass the variable index to

$.GetOptionKey
Reply all
Reply to author
Forward
0 new messages