title: Go HTML templates: something similar to Jinja2 macros?
body: <p>This is partly a follow-up to my earlier <a href="https://stackoverflow.com/questions/55913146/go-html-templates-defining-array-of-array-of-strings-to-range-over">question</a>. The problem I'm trying to solve now is converting Jinja2 macros with arguments, e.g., something like</p>
  
  <pre><code>{% macro example(arg1, arg2) %}
  {% if arg1 %}
     do something with arg1 and arg2
  {% endif %}
  {% endmacro %}
  </code></pre>
  
  <p>AFAICT, in Go, the nearest equivalent are nested templates, e.g.,</p>
  
  <pre><code>{{define "example"}}
  {{if .Arg1}}
      do something with .Arg1 and .Arg2
  {{end}}
  {{end}}
  </code></pre>
  
  <p>However, whereas in Jinja <code>arg1</code> and <code>arg2</code> are what I'd call true arguments, i.e., when you call the <code>example</code> macro you invoke it as <code>{{example(par1, par2)}}</code>, in Go, you use <code>{{template "example" .}}</code> and the dot is analogous in my mind to an undefined (or not clearly defined) global workspace.</p>
  
  <p>The problem is when those arguments are defined in the calling template, i.e., let's say that in Jinja it's called as <code>{{example("somestring", "another")}}</code> in one template and two other strings in another template. I thought I could use variables to pass the information, e.g., <code>{{$arg1 := "somestring"}}</code> and then invoke the template, or even define the variable in the same action as the invocation, but Go keeps complaining <code>undefined variable "$arg1"</code> so it doesn't seem to be possible.</p>
  
  <p>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 <code>upper()</code> and <code>lower()</code>--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.</p>
  
  <p>Is there any hope for a solution with Go templates or should I just give up and use something else?</p>