Joe Abbate
Joe Abbate

Reputation: 1750

Go HTML templates: something similar to Jinja2 macros?

This is partly a follow-up to my earlier question. The problem I'm trying to solve now is converting Jinja2 macros with arguments, e.g., something like

{% macro example(arg1, arg2) %}
{% if arg1 %}
   do something with arg1 and arg2
{% endif %}
{% endmacro %}

AFAICT, in Go, the nearest equivalent are nested templates, e.g.,

{{define "example"}}
{{if .Arg1}}
    do something with .Arg1 and .Arg2
{{end}}
{{end}}

However, whereas in Jinja arg1 and arg2 are what I'd call true arguments, i.e., when you call the example macro you invoke it as {{example(par1, par2)}}, in Go, you use {{template "example" .}} and the dot is analogous in my mind to an undefined (or not clearly defined) global workspace.

The problem is when those arguments are defined in the calling template, i.e., let's say that in Jinja it's called as {{example("somestring", "another")}} in one template and two other strings in another template. I thought I could use variables to pass the information, e.g., {{$arg1 := "somestring"}} and then invoke the template, or even define the variable in the same action as the invocation, but Go keeps complaining undefined variable "$arg1" so it doesn't seem to be possible.

I know I can "push" the definition of the strings to the calling Go code, but aside from complicating the calling tree, this doesn't feel right because after all the template is presentation code and those strings are part of the presentation, not the business logic. And it's not just string arguments, there are (a) instances of formatting functions (like upper() and lower()--I know I can define them in a funcmap) and (b) HTML formatting macros that, for example, take a CSS class attribute as one of the arguments.

Is there any hope for a solution with Go templates or should I just give up and use something else?

Upvotes: 5

Views: 11145

Answers (1)

Liyan Chang
Liyan Chang

Reputation: 8051

Go templates are intentionally pretty basic. You're going to find that most of the time when you're looking for something that doesn't seem possible, you probably will end up solving it with a golang function. It helps keep templates simpler and pushes code into golang functions which are far more testable.

https://golang.org/pkg/html/template/#Template.Funcs

Alternatively, there are a number of alternative templating engines that are more full featured.

Upvotes: 6

Related Questions