When should one pass data to a template and when call a function?

Viewed 52

When having passed functions to a template via Funcs, these can be called directly in the template. Data can also be passed via Execute.

So far, I've passed general data to the template and only called functions when for example I had to format a Time or some String. See below.

Combining both:

{{range .AssignedTickets}}
  <p>FormatDate .Date</p>
  <p>{{FormatEditorName .EditorID}}</p>
{{end}}

Mostly using functions, assuming only EditorID was passed as data:

{{$assignedTickets := GetAssignedTickets .EditorID}}
{{range $assignedTickets}}
  <p>FormatDate .Date</p>
  <p>{{FormatEditorName .EditorID}}</p>
{{end}}

When should I pass data and when should I call a function? Are there performance reasons as to avoid one of these (I'd guess I should avoid calling functions inside the template?)

1 Answers

The big advantage of data passed in is: It is constant. If you call a functions twice (e.g. current date) it might return two different values (e.g. if one call happened right before midnight and the other after midnight). Also: Functions which may fail are best handled outside the template.

Calling formatting functions (display logic): yes as these functions are deterministic and do not fail. Calling business logic: No.

Related