Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pass multiple objects to go template?

Tags:

templates

go

Most examples I can find describe very simple/basic things, such as showing attributes of a person object like this:

The name is {{.Name}}. The age is {{.Age}}.

What happens if you have a more complicated web page, for example, multiple different objects and lists of objects, i.e. How do you do something like this:

{{p.Name}} is aged {{p.Age}}. 
Outstanding invoices {{invoices.Count}} 

<table>
<tr><td>{{invoices[0].number}}</td></tr>
.... etc...
like image 423
Jay Avatar asked May 22 '14 08:05

Jay


People also ask

What is dot in Go template?

Anything within {{ }} inside the template string is where we do something with the data that we pass in when executing the template. This something can be just displaying the data, or performing certain operations with it. The . (dot) refers to the data that is passed in.

What is a Go template?

Go's template is designed to be extended by developers, and provides access to data objects and additional functions that are passed into the template engine programmatically. This tutorial only uses functions universally provided in the text/template package, and does not discuss the specifics of data access.


2 Answers

You can declare and pass in an anonymous struct like this:

templ.Execute(file, struct {
    Age int
    Name string
}{42, "Dolphin"})

and access the variables like:

{{.Age}}, {{.Name}}

While this still requires you to make a struct, it is among the most concise ways to do it. You'll have to decide if it is too ugly for you ;)

like image 96
Rick Smith Avatar answered Sep 22 '22 05:09

Rick Smith


You can put your more complex data into struct, and pass it just like you did Name and Age. For example,

type vars struct {
    P User
    Invoices []Invoice
}

type User struct {
    Name string
    Age int
}

type Invoice {
    Number int
    Description string
}

If you pass an instance of vars into the template execution, you can reference sub-structures by using dots and array indexes, just like in regular go code.

{{.P.Name}}, {{.P.Age}}, {{.Invoices[0].Number}}
like image 21
Paul Hankin Avatar answered Sep 24 '22 05:09

Paul Hankin